是否可以在 Laravel 9 中更改请求的正文内容和路径?

Is it possible to change the body content and path of a request in Laravel 9?

我目前正在尝试编写一个中间件来从请求的路径和内容中过滤某些表达式。我知道可以分别使用 $request->path()$request->getContent() 读取 URI 和原始正文内容,但找不到更改它的方法。

我想到的代码如下所示:

<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;

class MyMiddleware
{
  public function handle(Request $request, Closure $next)
    $uri = $request->path();
    $body_content = $request->getContent();
    $request->setContent(str_replace("foo","bar",$body_content));
    $request->setPath(str_replace("foo","bar",$uri));
    //functions setContent() and setPath() don't exist
    return $next($request);

}

Laravel 是否有我找不到的功能,或者如果没有,我该如何处理?

是的,您可以在中间件中修改传入的请求。事实上,您的中间件可以扩展 Illuminate\Foundation\Http\Middleware\TransformsRequest class, that already have a bunch of useful methods to help you so. All you had to do is override transform method. You can see how it's done in ConvertEmptyStringsToNull 中间件。

我现在通过使用修改后的内容创建一个新请求来解决这个问题:

public function handle(Request $request, Closure $next)
{
    $uri = $request->path();
    $body_content = $request->getContent();
    //process $uri and $body_content here
    $final_request = Request::create($uri, $request->method(), $request->query->all(), $request->cookies->all(), $request->allFiles(), $request->server->all(), $body_content);
    return $next($final_request)
}