Search code examples
phplaravellaravel-middlewarelaravel-9

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


I'm currently trying to write a middleware to filter certain expressions from a request's path and content. I know it's possible to read the URI and raw body content using $request->path() and $request->getContent() respectively, but can't find a way to change it.

The code I have in mind would look something like this:

<?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);

}

Does Laravel have functions for this that I can't find, or if not, how would I go about this?


Solution

  • I now solved this by creating a new request with the modified contents like this:

    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)
    }