Laravel: How to create the correct route group for localization?

Now I am writing examples of routes without grouping to localize my Laravel project:

Route::get('/{lang?}', function($lang=null){
    App::setlocale($lang);
    return view('welcome');
});

How can I correctly create a route group for more than one language with a prefix or with an argument instead of a prefix or using domain routing in Laravel 5.6? And localization can be created in the domain prefix and routing examples:

http://website.com/en
http://en.website.com
+4
source share
2 answers

You can use a group in routes to manage multiple routes, and then apply functionality to them, such as middleware. For instance:

Route::group([ 'middleware' => 'name', 'namespace' => 'prefix' ], function($router){
    $router->get('/xyz','Controller@function);
});
0
source

Well here is my best attempt:

Keep all route definitions, for example. web.php

RouteServiceProvider:

Route::group([ 
    'domain' => '{lang}.example.com'
    'middleware' => LangMiddleware::class,
    'namespace' => $this->namespace // I guess?
], function ($router) {
     require base_path('routes/web.php');
});

, , :

Route::group([
        'middleware' => LangMiddleware::class,
        'namespace' => $this->namespace,
        'prefix' => {lang} //Note: This works but is undocumented so may change
], function ($router) {
    require base_path('routes/stateless.php');
});

LangMiddleware , - :

class LangMiddleware {
     public function handle($request, $next) {
          if ($request->route("lang")) {
               // also check if language is supported?
              App::setlocale($request->route("lang"));
          }
          return $next($request);          
     }         
}
0

Source: https://habr.com/ru/post/1695093/


All Articles