3

How can I prevent the Route prefix from being passed to all the child routes controller functions as the first parameter? It is messing with the $id parameter of my child routes!

Route::prefix('{locale?}')->middleware(['locale.default', 'locale'])->group(function() { Route::get('/car/{id}', [ 'uses' => 'CarController@getCar', 'as' => 'car', 'middleware' => 'auth' ])->where(['id' => '[0-9]+']); }); 

In CarController's getCar() function, the id parameter is getting the locale (en, fr, it) instead of the id of the car being passed.

public function getCar($id) { $car = Car::where('id', $id)->firstOrFail(); } 

To fix this, I must do:

public function getCar($locale, $id) { $car = Car::where('id', $id)->firstOrFail(); } 

Is there a way to simply prevent the passing of $locale to the child route's controller functions so that I don't have to add $locale as the first parameter to every function?

If I change the getCar() parameter from $id to $request of type Request, I can do this and it works. Is this a good solution?

public function getCar(Request $request) { $car = Car::where('id', $request->id)->firstOrFail(); } 

The Laravel 5.6 docs seems to say that this can be done: https://laravel.com/docs/5.6/requests

Accessing The Request Via Route Closures

You may also type-hint the Illuminate\Http\Request class on a route Closure. The service container will automatically inject the incoming request into the Closure when it is executed:

use Illuminate\Http\Request;

Route::get('/', function (Request $request) { //... });

Can anyone confirm this please? Thanks!

3 Answers 3

3

Using a middleware, you simply need to add this line to the handler:

$request->route()->forgetParameter('prefix'); 
Sign up to request clarification or add additional context in comments.

Comments

1

It would be wiser to use service provider for setting up the locale.

This article should guide you through the architecture for the multi-language and Laravel.

https://learninglaravel.net/forum/laraveltutorials/how-to-use-multiple-languages-in-your-laravel-5-website

All the best.

1 Comment

Thanks for replying. This is exactly what I did. As can be seen in my code, I have 2 custom Middleware for handling the locale and setting the default local.
0
public function callAction($method, $parameters) { unset($parameters['prefix']); return parent::callAction($method, $parameters); } 

This should be called in your controller.

https://laracasts.com/discuss/channels/laravel/ignoring-few-route-parameters

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.