Managing Laravel 4 Localization

In this article I will explain how to implement a quick solution for setting up session and cookie based localization in your Laravel 4.2 app.


First, we need to set up our configuration file. It has a default locale, but it does not have an array of available locales, which can be used. So, we will create a new variable with available locales in our config. That is required — so that user will only be able to select out of available locales.


Next we need a way to set a locale and also save it to user session so it would be available later. So we create a new method in a controller (I use a base controller — but that really does not matter much).

And we need to add a route for this method in the router:


We will use the Laravel App::before() method — to setup the application locale on each request. App/filters.php already has the method declared, so we can add the code there. (Thats ok for this tutorial).


Conclusion

Thats it! Now you can add the ‘locale/{locale}’ route to your application, and when a user clicks a link — his locale will be switched to the one you have set for him.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.