Search code examples
phplaravellaravel-routing

Laravel - locale optionally as first parameter in the URL


I've come more from a vanilla PHP background, but I'm starting to get into Laravel (and Lumen). I am working on an internationalised project and putting together the URL structure.

I am a fan of the Apple example, i.e. apple.com/mac gives you the Mac products on Apple's US site. apple.com/uk/mac gives you the Mac products on Apple's UK site (i.e. apple.com/{locale/?}route)

Is it possible with Laravel to replicate this behaviour:

  1. Is the first parameter one of our known locales
  2. If so, set the locale and carry on
  3. If not, does the parameter match one of our registered routes and carry on

I've seen some answers to similar questions saying that the locale as an optional parameter 1 isn't possible because then "the router will not know what to do", but there are real-life examples, Apple being the one that I've given (and also in some vanilla projects that I've worked on), where this is done.

Please could you advise?


Solution

  • So the way to go with this easily is using the package @BlackXero mentioned.

    $localiseGroup = [
        'prefix' => LaravelLocalization::setLocale(),
        'middleware' => ['localeSessionRedirect', 'localizationRedirect',]
    ];
    
    Route::group($localiseGroup, function() {
    
        Route::get('/mac', '<handler>');
    
    });
    
    // domain.com/mac and domain.com/es/mac would now work
    

    If you read the docs, you'll see all of the setup instructions to make it work as expected.