Search code examples
phplaravellaravel-5laravel-5.1middleware

laravel 5.1 - rewrite url variable in middleware then pass new value to additional middleware and controller


I wish to manipulate the url variable in middleware then to pass new vaule to some additional middleware for checking, then pass new value to controller

Arbitrary example: domain.com/1 -> middleware to add 3 to 1 -> middleware to check new number 4 against database -> pass new number to controller

My route:

Route::get('{v}', [
        'middleware' => ['rewrite','dbCheck'],
        'uses' => 'video@search'
    ]);

I get the variable in the middlewares using $v = $request->v; - how do I return the rewritten variable to the next middleware and ultimately the controller?

I've tried resetting the variable afterwards using $request['v'] = $v; with no joy


Solution

  • Every time you try to read a value from Request object, it merges all available sources of data (POST/GET arrays, query string, route parameters) and fetches the value from merged result. Therefore, if you want to modify the value that will be returned when you try to fetch it from the Request, you need to modify not the request object, but the source.

    In your case you want to modify value of the route parameter - the following code will work for you:

    $request->route()->setParameter('v', $request->v + 3);