[Laravel] Implementation of multilingual switching function

Sep 4, 2020 PHP Laravel

A memorandum, the fourth.

Continuation of "[Vue.js] Multilingualization using vue-i18n” that I wrote last time. I implemented a switching function in Laravel.

reference: https://mydnic.be/post/laravel-5-and-his-fcking-non-persistent-app-setlocale

Implementation

First, prepare the language to be used as an array.

<? php

return [
    'ja' =>'Japanese',
    'en' =>'English',
    'cn' =>'Simplified Chinese',
    'tw' =>'Traditional Chinese',
];;

?>

Next, prepare a controller to write the language switching process.

$ php artisan make: controller LanguageController
class LanguageController extends Controller
{
    public function switchLang ($ lang)
    {
        // When there is lang passed as an argument in the prepared language array
        // Save key (applocale): value ($ lang) in session
        if (array_key_exists ($ lang, Config :: get ('languages'))) {
            Session :: put ('applocale', $ lang);
        }
        return Redirect :: back ();
    }
}

Create middleware.

$ php artisan make: middleware Language

setlocale () is a method to set locale information.

class Language
{
    / **
     * Handle an incoming request.
     *
     * @param \ Illuminate \ Http \ Request $ request
     * @param \ Closure $ next
     * @return mixed
     * /
    public function handle ($ request, Closure $ next)
    {
        if (Session :: has ('applocale') AND array_key_exists (Session :: get ('applocale'), Config :: get ('languages'))) {
            App :: setLocale (Session :: get ('applocale'));
        }
        else {
            App :: setLocale (Config :: get ('app.fallback_locale'));
        }
        return $ next ($ request);
    }
}

When you add new middleware, don’t forget to add it to the kernel.

protected $ middlewareGroups = [
        'web' => [
            \ App \ Http \ Middleware \ EncryptCookies :: class,
            \ Illuminate \ Cookies \ Middleware \ AddQueuedCookiesToResponse :: class,
            \ Illuminate \ Session \ Middleware \ StartSession :: class,
            // \ Illuminate \ Session \ Middleware \ AuthenticateSession :: class,
            \ Illuminate \ View \ Middleware \ ShareErrorsFromSession :: class,
            \ App \ Http \ Middleware \ VerifyCsrfToken :: class,
            \ Illuminate \ Routing \ Middleware \ SubstituteBindings :: class,
            \ App \ Http \ Middleware \ Language :: class,
        ],,

Set the routing.

Route :: get ('lang / {lang}', ['as'=>'lang.switch','uses' =>'LanguageController @ switchLang']);

Add a dropdown to the navigation bar.

        <li class = "nav-item dropdown" id = "nav-lang">
          <a href="#" class="nav-link dropdown-toggle" data-toggle="dropdown">
            {{Config :: get ('languages') [App :: getLocale ()]}}
          <span class = "caret"> </ span> </a>
          <ul class = "dropdown-menu">
            @foreach ((array) Config :: get ('languages') as $ lang => $ language)
              @if ($ lang! = App :: getLocale ())
                <li>
                  <a href="{{route('lang.switch', $ lang)}} "> {{$ language}} </a>
                </ li>
              @endif
            @endforeach
          </ ul>
       </ li>

When you move it, it looks like this Screenshot 2020-09-04 23.10.33.png drop down Screenshot 2020-09-04 23.11.01.png Let’s choose English Screenshot 2020-09-04 23.11.27.png It switched successfully!