Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.4: How to DO NOT use route parameter in controller

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');
});
like image 209
Renan Coelho Avatar asked Sep 15 '25 15:09

Renan Coelho


1 Answers

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.

like image 167
thephper Avatar answered Sep 17 '25 07:09

thephper