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' session variable, and mydomain.com/he/bla 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?
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
- Using similar_text and strpos together
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.
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:
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:
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:
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)
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:
PS. The links are specially useful if you add them to your master template file.