How to make switching language button

Hallo, i'm using blade template, all file content is in view and i need 2 language on my project, how the easiest way to make the button switcher language? can someone help me?

Thank you

wiyono
wiyono
  • 2 years ago

this may not be the complete solution but you can do something like this:

class HomeController extends BaseController {

    public function postChangeLanguage() 
    {
        $rules = [
        'language' => 'in:en,fr' //list of supported languages of your application.
        ];

        $language = Input::get('lang'); //lang is name of form select field.

        $validator = Validator::make(compact($language),$rules);

        if($validator->passes())
        {
                        Session::put('language',$language);
            App::setLocale($language);
        }
        else
        {/**/ }
    }
}

and you can create a form like this:

{{ Form::open(['action' => 'HomeController@postChangeLanguage']) }}
    {{Form::select('lang',['en'=>'en','fr'=>'fr'],$lang,['onchange'=>'submit()'])}}
{{ Form::close()}}

and in your App before filter

App::before(function($request)
{
   $language = Session::get('language','en'); //en will be the default language.
   App::setLocale($language);
});
App::setlocale($language);

This is only set for the current request - you will need to save the setting in a session and assign every page load (for example in global.php)

I was just editing my reply @martinhearn :)

Hallo @usm4n, thank you, i will try it...
Hallo @martinhearn, i muss put button select language, thank you

:) @usm4n

although perhaps better to retrieve the default language from the config rather than hardcode:

$language = Session::get('language',Config::get('app.locale'));

@martinhearn yes sure, you are right :)

Thanks man, its working perfect.

it's not clear

I know it's late but have you tried https://github.com/ied3vil/LanguageSwitcher ?