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:
- Is the first parameter one of our known locales
- If so, set the locale and carry on
- 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?
Answer
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.
Related Questions
- → "failed to open stream" error when executing "migrate:make"
- → October CMS Plugin Routes.php not registering
- → OctoberCMS Migrate Table
- → OctoberCMS Rain User plugin not working or redirecting
- → October CMS Custom Mail Layout
- → October CMS - How to correctly route
- → October CMS create a multi select Form field
- → October CMS - Conditionally Load a Different Page
- → How to disable assets combining on development in OctoberCMS
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → OctoberCms component: How to display all ID(items) instead of sorting only one ID?
- → In OctoberCMS how do you find the hint path?
- → How to register middlewares in OctoberCMS plugin?