Martin AJ Martin AJ - 1 month ago 10
PHP Question

How can I implement localization when there is multiple dynamic values in the URL?

The documentation of laravel says:


You may also change the active language at runtime using the setLocale method on the App facade:

Route::get('welcome/{locale}', function ($locale) {
App::setLocale($locale);

//
});



Also it says:


The default language for your application is stored in the
config/app.php
configuration file.


Which means if there isn't any value which specifics the language, then laravel will be used of the default language (which is defined there).




Ok well, what about when there is a dynamic value in the URL? I mean how can I detect the language when there either is or isn't
{locale}
in the URL. For example:

Route::get('post/{locale}/{id}', function ($locale, Request $request) {
App::setLocale($locale);
$post_id = $request->segment(2);
// search in the database based on $post_id
});


As you see, I've got post id of the URL by using
segment(2)
. But it won't work all the time. Because sometimes
{locale}
will not be set (and we expect laravel uses default language). In that case I need to use
segment(1)
to achieve post id.

Anyway, how can I implement localization when there is other dynamic values in the URL?

Answer

You may change your route as:

Route::get('post/{id}/{locale?}', function ($id, $locale = null, Request $request) {
   if(! is_null($locale)) {
      App::setLocale($locale);
   }
   $post_id = $id;
   // search in the database based on $post_id
});

Docs

Its called Optional Parameters

Comments