Laravel 5: Views – language: set persisting language selector

Views: set persisting language selector

Laravel is ready to serve multi-language sites.

After I have done this session based solutions I thought of cookies.
Cookies may even be a better solution, since once user selects language, he may want to come back to the same language selection during next visit.
But since milk is already spilled and it is easy to redo it for cookies, I am going to live it the way it is.

It is very easy to make site multi-language.
All you have to do, to change language, is to use this code:

But when you change language in Laravel, it refuses to persist, when you change page, and reverts to default.

Session based persistence

It is easy to remedy that.
Just follow this step-by-step explanation.

step 1:

Go to this file:  config\app.php and set up an array of valid languages.

step 2:

Make SetLocale middleware (you can name it anything):

and register it in: app\Http\Kernel.php inside of web middleware group:

And here is our middleware code:

 

step 3:

Create language switch route in web.php

step 4:

Add language switch drop down in: resources\views\home.blade.php

step 5:

Now, we have to make sure our selected language persists after page change.
To make that work, we actually have to re-apply selected language during every request / page change.

Unless you use your own logout process, code that logs out user is located in:

Inside of AuthenticatesUsers find method logout() and add two extra lines (persist) – as shown below:

And you are done.
Now, you have persisting locale.

Cookie based persistence

You can also attempt to use browser stored cookies to assure persistence.
When using cookies, you do not need to use step 5, as cookies are not destroyed with session end.

Of course, you also have to use cookie setters/getters instead of session used above.