mercredi 22 janvier 2020

Laravel blade language switcher for multi-language site

I'm looking for a simple way to switch language on my web app.

I have a blade header with language links. When the user clicks the link, I want the page to refresh in the correct language:

<ul>
    @foreach (config('app.available_locales') as $locale)
       <li>
           <a class="simple-link" href="?????" ></a>
       </li>
    @endforeach
</ul>

My problem is that I don't know what to use in the href. I'm fairly new to blade (I usually use VueJS with Laravel)

Here is how my project works.

All my links are structured that way:

www.domain.com/language/page

So all my routes look like this:

fr.home.index
fr.offers.index

and so on. Here is my web.php routes class:

Route::domain(config('app.url'))->group(function () {

Route::redirect('/', '/' . Loc::current(), 301);  

Route::locales(function() {

    // Home
    Route::get(__('routes.home.index'), 'Home\HomeController@index')->name('home.index');
    Route::get(__('routes.home.faq'), 'Home\HomeController@faq')->name('home.faq');
    Route::get(__('routes.home.about'), 'Home\HomeController@about')->name('home.about');
    Route::get(__('routes.home.terms'), 'Home\HomeController@terms')->name('home.terms');
    .
    .
    .
    .
   });

});

I have a middleware to handle the locale for each request:

class SetLocale
{
   public function handle($request, Closure $next)
   {
       $segment = $request->segment(1) ? $request->segment(1) : Loc::fallback();

       if (!Loc::isSupported($segment)) {
           abort(404, 'Locale is not supported');
       }

       Loc::set($segment);

       return $next($request);
   }
}

All my routes are translated. I have a routes.php in every resources/lang/ folders:

return [
  'home' => [
        'index' => '',
        'faq' => 'frequently-asked-questions',
        'about' => 'who-are-we',
        'terms' => 'terms-and-conditions',
        'legal' => 'legal-notice',
        'label' => 'label',
    ],
    .
    .
    .
    .
    .
]

Can someone help me please? I've been trying to find a solution for way longer than I'd want to admit!

TIA.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire