How to set language (locale) inside a Route::group

2019-07-25 07:50发布

问题:

Inside blade - welcome.blade.php.

 <div class="links">
      <a href="https://laravel.com/docs">{{ __('passwords.reset') }}</a>
 </div>

Inside web.php.

If I run:

Route::get('/', function () {
    return view('welcome');
});

I get the correct welcome blade page with the correct translation.

Another Route:

Route::get('welcome/{lang}', function ($lang) {
//    echo $lang;
//    dd(Lang::getLocale());
    App::setLocale($lang);
    //dd(Lang::getLocale());
    return view('welcome');    
    //
});

If I run dd(Lang::getLocale()); I can see the correct language sent by the URL http://testapp/welcome/en. In this case 'en'. If I put dd() in comment I can see the correct translation in Laravel Welcome page.

But when I run this code:

Route::group(['prefix'=>'welcome'], function (){    
    Route::group(['prefix'=>'{lang}'], function ($lang){
        //echo $lang;
        //dd(Lang::getLocale());
        App::setLocale($lang);
        //dd(Lang::getLocale());
        return view('welcome');            
    });
});

This is what I have:

echo $lang; gives me ErrorException in web.php line 30: Object of class Illuminate\Routing\Router could not be converted to string

dd(Lang::getLocale()); gives me 'en'.

App::setLocale($lang); gives me 404 Not Found

App::setLocale($lang); AND return view('welcome'); gives me 404 Not Found

return view('welcome'); gives me 404 Not Found

And When I run

App::setLocale($lang);
dd(Lang::getLocale());
return view('welcome');

I get an object:

Router {#21 ▼
  #events: Dispatcher {#23 ▶}
  #container: Application {#3 ▶}
  #routes: RouteCollection {#25 ▶}
  #current: null
  #currentRequest: null
  #middleware: array:6 [▶]
  #middlewareGroups: array:2 [▶]
  +middlewarePriority: array:6 [▶]
  #binders: []
  #patterns: []
  #groupStack: array:3 [▶]
}

So, my guess is that Route::group(['prefix'=>'{lang}'... is returning a object not a string. This is why it crashes the process.

How can I solve this issue using Route::group()?

回答1:

The problem is that Route::group is just a wrapper to organize and group other routes. It is not a defined url. Route::group and Route::post/get don't work that same, so you cannot put logic inside a Route::group call.

What you can do is the following

Route::group(['prefix'=>'welcome'], function (){    
    Route::group(['prefix'=>'{lang}'], function (){
        Route::get('/', function ($lang) {
            App::setLocale($lang);
            return view('welcome');
        });            
     });
});