Matthias
Matthias

Reputation: 275

How to create a multi language website with Laravel 9

What is the best way to setup a multi language website with Laravel? The URL must contain the language (nl, fr, en). For example: mywebsite.com/en/faq. Most examples and tutorials I find use the session to store the current language which is completely useless of course. I should be able to directly link to a page in a specific language.

I could create a route per language but that does not really seem like a good idea. Ideally this could be made dynamic in order to easily create more locales.

Upvotes: 1

Views: 3208

Answers (4)

Hosam Saleh
Hosam Saleh

Reputation: 11

You can use the Mcamara Laravel localization package. it'll do everything you need. And here's the package link:

https://github.com/mcamara/laravel-localization

Upvotes: 0

Matthias
Matthias

Reputation: 275

I ended up using the laravel-localization package by mcamara. Seems to do everything I need. I'm not really sure why anyone would try to build their own version if this exists.

Upvotes: 1

Akhzar Javed
Akhzar Javed

Reputation: 628

You can do something like this, create route with locale group and locale middleware

Route should look like this enter image description here

And then in your middleware set the language based on the locale parameter.

We can pick dynamic url segment using request()->route('')

enter image description here

Note: You need to pass locale value when you call route() helper.

Maybe there is another better approach to it.

Upvotes: 0

Juranir Santos
Juranir Santos

Reputation: 429

I'm curious, why you cannot use session (it's a true question, I really would like to understand)?

You can use the same approach than with session: create a middleware to set App::setLocale("YourLanguage") based on query string.

public function handle(Request $request, Closure $next)
{
    // This example try to get "language" variable, \
    // if it not exist will define pt as default \
    // you also can use some config value: replace 'pt' by Config::get('app.locale')

    App::setLocale(request('language', 'pt'));

    return $next($request);
}

Or you can do it by Route:

// This example check the if the language exist in an array before apply
Route::get('/{language?}', function ($language = null) {
    if (isset($language) && in_array($language, config('app.available_locales'))) {
        app()->setLocale($language);
    } else {
      app()->setLocale(Config::get('app.locale'));
    }
    
    return view('welcome');
});

Source:

Laravel change language depending on a $_GET parameter

https://lokalise.com/blog/laravel-localization-step-by-step/

Upvotes: 0

Related Questions