mercredi 6 octobre 2021

How to switch between languages in laravell

I'm new to laravell and would like to understand how to switch between two Languages the best way.

My website only uses two languages. I want to build a simple language switcher. Here is my HTML -> Which should display the language that I want to switch to. Not show the current language.

For example. If i am on www.test.com/en my html says

            <a class="lang-switch">German</a>

So when i click on it i land on

www.test.com/de

And now my html should say

                <a class="lang-switch">English</a>

Here is how i do my language routing.

Route::get('/{locale?}', function ($locale = null) {
    if (isset($locale) && in_array($locale, config('app.available_locales'))) {
        app()->setLocale($locale);
    }

    return view('home');
});

Route::get('/{locale?}/contact/', function ($locale = null) {

    if (isset($locale) && in_array($locale, config('app.available_locales'))) {
        app()->setLocale($locale);
    }

    return view('contact');
});

I need this switch to work on both websites since it's a static nav bar.

I register my locales in my app.php file

        'available_locales' => [
        'English' => 'en',
        'German' => 'de',
    ],

I created a Language Controller but i'm not sure how to implement or use it correctly.

    class LanguageController extends Controller
    {
      public function switchLang($lang)
        {
          if (array_key_exists($lang, Config::get('languages'))) {
             Session::put('applocale', $lang);
          }
          return Redirect::back();
        }
    }


from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2WLF6Mr
via IFTTT

Aucun commentaire:

Enregistrer un commentaire