P
P
Pavel Konchich2021-01-21 02:54:31
Laravel
Pavel Konchich, 2021-01-21 02:54:31

Multilingual laravel 8 with prfixes in the route?

Good night all. Question from the same opera.
It is necessary to implement multilingualism. Actually, I implemented it, but I can’t understand how it’s more correct (or rather, “how” in general) to set localization with redirects to prefixes, depending on the user’s language preference.

Web.php

Route::group(['namespace' => 'Site', 'middleware' => 'set locale', 'prefix' => '{locale}',
        'where' => ['locale' => '[a-zA-Z]{2}'],], function() {
        // Base websites Urls
        Route::get('/', '[email protected]')->name('home');
       
    });

// Site routes


SetLocale.php - Middleware
public function handle(Request $request, Closure $next)
    {
       
        app()->setLocale($request->segment(1));

        return $next($request);
    }


How to manually add or without prefixes - I have already decided - it is necessary that, depending on roughly speaking, $_SERVER['HTTP_ACCEPT_LANGUAGE']I can parse it into routes automatically and not prescribe everything in 100 controllers.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Pavel Konchych, 2021-01-21
@konchychp

Until they give me a more concise solution, or rather I find it myself, just not at 3 in the morning, I will leave it that way for the dev version for now. Maybe someone will need my version
of web.php

Route::get('locale/{locale}', 'Site\[email protected]')->name('locale');

Route::group(['middleware' => 'locale'], function(){
    Route::get('/', function () { return redirect (app()->getLocale(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2))); });
});

Route::group(['namespace' => 'Site', 'middleware' => 'locale', 'prefix' => '{locale}',
    'where' => ['locale' => '[a-zA-Z]{2}'],], function() {

    // Base websites Urls
    Route::get('/', '[email protected]')->name('home');
});

// Site routes

SetLocale.php - middleware
public function handle(Request $request, Closure $next)
    {
        App::setLocale(substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2));
        return $next($request);
    }

Routes in home.blade.php
href="{{ route('bonus', [app()->getLocale()])}}

V
Vladimir Kokhan, 2021-01-21
@SkazochNick

Look here
There for the 5th Lara, but works on the 8th too. Checked.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question