7

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
Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125
  • Tag me when someone experienced answers, this is interesting to me (no idea sry) – abr Mar 20 '18 at 09:23
  • @abr do you see little star below voting chevrons thats how you bookmark a question ;); regarding OP; you do it via package maybe like https://github.com/mcamara/laravel-localization. If you want to roll your own you will have to use middleware. – Kyslik Mar 20 '18 at 09:25
  • Ok, I'll teg to you @abr – Andreas Hunter Mar 20 '18 at 09:25
  • Maybe this can help: https://stackoverflow.com/questions/28482985/route-using-either-a-prefix-or-a-domain – Hedegare Mar 20 '18 at 09:44

2 Answers2

2

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/web.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);          
     }         
}
apokryfos
  • 38,771
  • 9
  • 70
  • 114
0

You can use group in routes to manage multiple routes and then apply functionality like middleware on them. For example:

Route::group([ 'middleware' => 'name', 'namespace' => 'prefix' ], function($router){
    $router->get('/xyz','Controller@function);
});
Andreas Hunter
  • 4,504
  • 11
  • 65
  • 125
kshitij
  • 642
  • 9
  • 17