Summer Sale! All accounts are 50% off this week.

BloomWebbAB's avatar

Change Laravel route parameter

In the platform I'm developing it's possible to request the user's company data by sending a GET request to the api/company/{id} API endpoint.

By default the id parameter is an integer but usually it's also possible to set it as a string: api/company/mine will retrieve the authenticated user's company data.

In order to allow this I created a middleware that intercepts the API call and replaces mine with the actual company ID. Unfortunately, my solution is not exactly what I had in mind.

Here's my current solution:

$request->merge([
    'id' => $request->user()->company
]);

This works by adding the id to the request's input so that it can be accessed later on using $request->input('id');, but the problem is that if I try to access $request->route('id') I still get the old value.

Is it possible to change the route parameter directly?

P.S.

Another solution that comes in my mind is to actually programmatically create a new request with the new parameter and then pass that one to the next() function in the middleware.

0 likes
5 replies
bestmomo's avatar

A simple way is to check the parameter in controller and, if it's a string get the id.

usman's avatar

@laracast-bloom It is best to isolate the two routes. The other way around this is to check for the id in your middleware, if it is string redirect again to the same route with the user id else forward the request. But I would still go with the first option.

Usman.

pmall's avatar

You can either have two routes and two controller actions or put a condition at the controller action level. Don't do this in a middleware, it is harder to understand.

JoshStar's avatar

I think you already found a workaround by now but I managed to find out how to do exactly what you wanted:

$request->route()->setParameter('id',  $request->user()->company);

This will allow you to access the id parameter in your controllers either via the $id method parameter or $request->route('id').

You'll still need to do $request->id = $request->user()->company; (or the merge thing you were doing) to change the $request->id/$request->input('id') version of the variable too.

franciscocaldeira's avatar

@JoshStar you can do $request->request->add(['id' => $request->user()->company]); it is shorter and adds to the parameters for the route (work up to laravel 8). For laravel 9 $request->merge(["key"=>"value"]) is the way to go.

Please or to participate in this conversation.