Laravel is a strong PHP framework that is widely used. Recently, I was developing with that framework and I needed to create a website with content in 2 languages: catalan and spanish.
To solve this problem you can use some options... like url with language or save language in session. I decided to use the last one.
I created this code:
filters.php
App::before(function($request) {
// We use the locale of the session
if ( Session::has('locale') ) {
App::setLocale(Session::get('locale'));
}
});
BaseController.php
class BaseController extends Controller {
public function switchLocale($lang) {
// We change the locale lang in the session and redirect back (see filter language in filters.php).
if ( in_array($lang, Config::get('app.available_language')) ) {
Session::put('locale', $lang);
}
return Redirect::back();
}
}
app.php
'locale' => 'es',
'fallback_locale' => 'ca',
'available_language' => array('es', 'ca'),
Finally, in our view we use this code in the links used to change the language:
Catalan -> URL::action('BaseController@switchLocale', array('ca'))
Spanish -> URL::action('BaseController@switchLocale', array('es'))
No comments:
Post a Comment