Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel: How to create correct routes group for localization?

Now I write sample routes without grouping for localization my Laravel project :

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

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

http://website.com/en
http://en.website.com
like image 460
Andreas Hunter Avatar asked Mar 20 '18 09:03

Andreas Hunter


1 Answers

Well here's my best try:

Keep all your route definitions in e.g. web.php

You can then use multi-domain routing in your RouteServiceProvider:

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

In addition, using the same routes you can also do prefixed route groups:

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');
});

This all relies on that LangMiddleware middleware class which can be something like:

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);          
     }         
}
like image 146
apokryfos Avatar answered Nov 09 '22 12:11

apokryfos