D
D
DocTypeMaster2021-02-15 13:13:01
Laravel
DocTypeMaster, 2021-02-15 13:13:01

How to make language selection in Laravel?

I am making one site and I need to make it multilingual, I found this code in the official Laravel 8 documentation:

use Illuminate\Support\Facades\App;

Route::get('/greeting/{locale}', function ($locale) {
    if (! in_array($locale, ['en', 'es', 'fr'])) {
        abort(400);
    }

    App::setLocale($locale);
});

As I understand it, it needs to be pushed into the web.

I did this and everything seems to be fine, the main one is translated, but the rest of the pages do not work in a different localization, I am already silent about the fact that the login does not open the page at all.

I eventually realized that "/" and "/ru" need 2 different routes, and I did it like this
Route::get('/', function () {
    return view('welcome');
});

Route::get('/{locale}', function ($locale) {
    if (! in_array($locale, ['en', 'ru'])) {
        abort(400);
    }

    App::setLocale($locale);
});

But, as I wrote earlier, everything except these two routes does not work at all. How to do it correctly, tell me (of the documentation did not explain this point at all).

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ivan Koryukov, 2021-02-15
@MadridianFox

I wouldn't try to support paths with and without language.
I think it's enough to / redirect to / ru, as habr.com does, for example, and all other links should always be done with the language.
Those. /en/posts/1 is fine, but /posts/1 is already an error.
Further, I would wrap everything, in general, all the routes in a group

Route::prefix('{lang}')->group(function () {
  //...
});

After that, I would write a middleware that takes the language code from the request and sets the locale.
And also, because language is a parameter in path, then for a non-existing language it is necessary to give the code 404, not 400.

R
Roman, 2021-02-20
@EDF

At one time, I used this package for this purpose in a small project:
https://github.com/mcamara/laravel-localization

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question