What's the best logic for switching language in Laravel?

后端 未结 8 1629
遥遥无期
遥遥无期 2020-12-23 02:29

I\'m using Laravel localization to provide two different languages. I\'ve got all the path stuff set up, and mydomain.com/en/bla delivers English and stores the \'en\' sessi

相关标签:
8条回答
  • 2020-12-23 02:42

    This is a post i posted originally on the laravel forums, but maybe it will help somebody else, so i post it here also.

    I had some trouble with building a easy language switcher for my app, and the info on the forums where a little bit old (some posts), so i made this simple piece of code that makes it supereasy to change language on your app on the fly.

    I have the language strings in my views as following:

    {{ __('languagefile.the_language_string'); }}
    

    And I get the languages with a URL, i think this is the best way, also its good for seo and for links that people share. Example:

    www.myapp.com/fi/support (Finnish)
    www.myapp.com/en/support (English)
    www.myapp.com/sv/support (Swedish)
    

    Ok, so the problem was that i wanted a easy way to change the language on the fly, without having to mess with sessions and cookies. Heres how i made it:

    Make a library in your libraries folder called chooselang.php

    Insert this code inside:

    class Chooselang extends HTML {
        /**
         * Generate a Language changer link.
         *
         * <code>
         *      // Generate a link to the current location,
         *      // but still change the site langauge on the fly
         *      // Change $langcode to desired language, also change the Config::set('application.language', 'YOUR-LANG-HERE')); to desired language
         *      // Example
         *      echo Chooselang::langslug(URI::current() , $langcode = 'Finnish' . Config::set('application.language', 'fi'));
         * </code>
         *
         * @param  string  $url
         * @param  string  $langcode
         * @param  array   $attributes
         * @param  bool    $https
         * @return string
         */
    
        public static function langslug($url, $langcode = null, $attributes = array(), $https = null)
        {
            $url = URL::to($url, $https);
    
            if (is_null($langcode)) $langcode = $url;
    
            return '<a href="'.$url.'"'.static::attributes($attributes).'>'.static::entities($langcode).'</a>';
        }
    
    }
    

    After this you are ready for getting your url switcher URL:s generated. Simply add them as you whould any other Blade links.

    Example how to generate links for Finnish, Swedish and English (with Blade)

      {{ Chooselang::langslug(URI::current() , $langcode = 'Fin' . Config::set('application.language', 'fi')); }}
      {{ Chooselang::langslug(URI::current() , $langcode = 'Swe' . Config::set('application.language', 'sv')); }}
      {{ Chooselang::langslug(URI::current() , $langcode = 'Eng' . Config::set('application.language', 'en')); }}
    

    The above will generate URL:s that are always on the current page, and change the lang slug to the one you want. This way the language changes to the one you want, and the user naturally stays on the same page. The default language slug is never added to the url.

    Generated urls look something like:

    <a href="http://localhost/laravel/public/support">Fin</a>
    <a href="http://localhost/laravel/public/sv/support">Swe</a>
    <a href="http://localhost/laravel/public/en/support">Eng</a>
    

    PS. The links are specially useful if you add them to your master template file.

    0 讨论(0)
  • 2020-12-23 02:44

    I've solved my problem by adding this to the before filter in routes.php:

    // Default language ($lang) & current uri language ($lang_uri)
    $lang = 'he';
    $lang_uri = URI::segment(1);
    
    // Set default session language if none is set
    if(!Session::has('language'))
    {
        Session::put('language', $lang);
    }
    
    // Route language path if needed
    if($lang_uri !== 'en' && $lang_uri !== 'he')
    {
        return Redirect::to($lang.'/'.($lang_uri ? URI::current() : ''));
    }
    // Set session language to uri
    elseif($lang_uri !== Session::get('language'))
    {
        Session::put('language', $lang_uri);
    }
    
    // Store the language switch links to the session
    $he2en = preg_replace('/he\//', 'en/', URI::full(), 1);
    $en2he = preg_replace('/en\//', 'he/', URI::full(), 1);
    Session::put('he2en', $he2en);
    Session::put('en2he', $en2he);
    
    0 讨论(0)
  • 2020-12-23 02:47

    You could have a Route to hand language change, for example:

    Route::get('translate/(:any)', 'translator@set');

    Then in the set action in the translator controller could alter the session, depending on the language code passed via the URL.

    You could also alter the configuration setting by using

    Config::set('application.language', $url_variable');

    Controller Example - translate.php

    public function action_set($url_variable)
    {
         /* Your code Here */
    }
    
    0 讨论(0)
  • 2020-12-23 02:52

    This question still comes in Google search, so here's the answer if you're using Laravel 4 or 5, and mcamara/laravellocalization.

    <ul>
        <li class="h5"><strong><span class="ee-text-dark">{{ trans('common.chooselanguage') }}:</span></strong> </li>
            @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
                <li>
                   <a rel="alternate" hreflang="{{$localeCode}}" href="{{LaravelLocalization::getLocalizedURL($localeCode) }}">
                       <img src="/img/flags/{{$localeCode}}.gif" /> {{{ $properties['native'] }}}
                   </a>
               </li>
            @endforeach
    </ul>
    

    NOTE that this example shows flags (in public/img/flags/{{locale}}.gif), and to use it you will need a bit of .css, but you can modify it to display the text if you want...

    FYI. The mcamara/laravellocalization documentation has examples and a LOT of helpers, so look through the documentation on github. (https://github.com/mcamara/laravel-localization)

    0 讨论(0)
  • 2020-12-23 02:54

    Just in case for future users if you want to use package for localization There is a great package at https://github.com/mcamara/laravel-localization. which is easy to install and has many helpers.

    0 讨论(0)
  • 2020-12-23 02:57

    Try use Session's. Somthing like this:

    Controller:

     class Language_Controller extends Base_Controller {
    
            function __construct(){
                $this->action_set();
                parent::__construct();
            }
    
           private function checkLang($lang = null){
             if(isset($lang)){
               foreach($this->_Langs as $k => $v){
                 if(strcmp($lang, $k) == 0) $Check = true;
               }
           }
            return isset($Check) ? $Check : false;
           }
    
           public function action_set($lang = null){
            if(isset($lang) && $this->checkLang($lang)){
                Session::put('lang', $lang);
                $this->_Langs['current'] = $lang;
                Config::set('application.language', $lang);
            } else {
                if(Session::has('lang')){
                    Config::set('application.language', Session::get('lang'));
                    $this->_Langs['current'] = Session::get('lang');
                } else {
                    $this->_Langs['current'] = $this->_Default;
                }
            }
            return Redirect::to('/');
        }
    }
    

    In Route.php:

    Route::get('lang/(:any)', 'language@set');
    
    0 讨论(0)
提交回复
热议问题