BenjaminRH BenjaminRH - 1 year ago 98
PHP Question

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

I'm using Laravel localization to provide two different languages. I've got all the path stuff set up, and delivers English and stores the 'en' session variable, and delivers Hebrew and stores the 'he' session variable. However, I can't figure out a decent way to provide a language-switching link. How would this work?

Answer Source

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
    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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download