I am developing a Multilingual application and trying to make a middleware to pass route {locale} prefix to URL. But now I do not need to use this {locale} parameter in controller, for example:
public function getPost(App\Post $post)
{
return view('welcome')->withPost($post);
}
But the code above does not work unless I change the App\Post $post
to $locale, App\Post $post
.
The problem is because I'll need to pass the $locale parameter whenever I create a new controller. That is not cool.
How to avoid passing $locale
parameter to all controllers? I do not need it because I already used it on my middleware.
UPDATE:
routes\web.php
Route::prefix('{locale}')->middleware('locale')->group(function () {
Route::get('/', 'PageController@getHome')->name('welcome');
Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');
...
// This route must be the last!
Route::get('/{post}', 'PageController@getPost')->name('post');
});
There is a forgetParameter()-method in Laravel's route class, that can remove a parameter from being parsed to controller methods.
It can be used e.g. in a middleware, by calling it like so:
$request->route()->forgetParameter('locale');
Then the parameter will be removed from the controller dispatcher's parameter property and thereby not get parsed on to the controller methods as parameter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With