Search code examples
phplaravellaravel-5parameterslaravel-routing

How to prevent a parameter from getting injected in controller methods in Laravel


I am creating a multilingual website in Laravel. I need urls to be like that:

https://website.com/en/admin/user/1
https://website.com/ar/admin/user/1

so my route file looks like that:

Route::group(['prefix' => '{locale}'], function(){
Route::middleware("locale")->group(function () {

Route::group(['prefix' => 'admin', 'as' => "admin.", "namespace" => "Admin"],function(){

    Route::get('login', 'LoginController@index')->name("signin")->middleware("Guest");
    Route::post('login', 'LoginController@login')->name('login')->middleware("Guest");

    Route::group(["middleware" => "Admin"], function (){

        Route::get('/', ["as" => "dashboard", "uses" =>'DashboardController@index']);
        Route::get('logout', 'LoginController@logout')->name('logout');
        Route::resource('users', 'UsersController');

    });

});

});
});

My middleware "locale":

    public function handle($request, Closure $next)
{

    URL::defaults(['locale' => $request->segment(1)]);
    if(in_array($request->segment(1), config('app.locales')))
    {
        app()->setLocale($request->segment(1));
    }
    return $next($request);

}

Now the problem is that when I try to call a use a route with parameters I have to add the locale as a first parameter. For example: this is a method in UsersController:

    public function destroy($locale, $id)
{
    //Any Code

}

I have to add $locale as a parameter to the method to be able to use the other parameters or the $id will have the value of the $locale which is "en", "ar" instead of the user id. So is there any way I can avoid that so my method will look like:

    public function destroy($id)
{
    //Any Code
}

Solution

  • You can build your routes for example like this:

    Route::group(['prefix' => app()->getLocale()], function(){
    

    so you will get rid of locale route parameter.