Reputation: 6763
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.
Upvotes: 5
Views: 12259
Reputation: 58182
Hit a similar issue, and with some digging through the laracasts forums, someone has noted down an alternative that I have successfully used:
$request->route()->setParameter('id', $request->user()->company);
Reference (last post): https://laracasts.com/discuss/channels/laravel/change-laravel-route-parameter
Upvotes: 12
Reputation: 6763
Found out that the best solution in this case, at least for me, was to deal with it in the request passed as a parameter in the controller action and in the model repositories.
The problem with creating a new request is that it's just partially working since the route parameters are not updated and it's not possible to update the route parameters manually without a lot of additional code.
Another possible solution is to redirect the request to the right API endpoint or deal with it in the controller.
Upvotes: 0