I try to set the local language when the user selects it, but it keeps going back to my default language when I refresh the page...
'locale' => 'en',
'locales' => ['fr', 'en', 'es'],
'fallback_locale' => 'fr',
So when the user selects another language, here is what I do (Seems like I tried everything :) ).
Any idea what else I can try?
public function setLang($lang){
App::setLocale($lang);
app()->setLocale($lang);
Session::put('locale', $lang);
setlocale(LC_ALL, $lang);
session(['locale' => $lang]);
return $lang;
}
If I set 'locale' to 'fr' in app.php, then it will be 'fr' by default.
[EDIT] Here is the javascript (vueJS) part, I call setLang through an axios call:
<div class="locale-changer" aria-labelledby="dropdown07">
<select class="dropdown-menu-lang " aria-labelledby="dropdown07" v-model="$i18n.locale" @change="langChanged($i18n.locale)" >
<option class="dropdown-item-lang" :selected="$i18n.locale == lang" v-for="(lang, i) in langs" :key="`Lang${i}`" :value="lang">{{ lang }}</option>
<!-- <option class="dropdown-item-lang" selected="true" :key="`Lang${i}`" value="fr">fr</option> -->
</select>
</div>
mounted(){
this.$i18n.Locale = localStorage.Lang;
console.log(" this.$i18n.Locale - " + this.$i18n.Locale); //it is OK here, the correct language which has been chosen by the user last time is displayed
},
methods: {
langChanged(lang){
localStorage.Lang=lang;
axios.get('/setlang/'+lang).then( );
}
}
You have to show the codebase where you actually call the setLang function.
Also you'll need to use some kind of persistence (maybe grab it from the URL or the Session)
I found out how to do this!
It was impossible to set $i18n.locale after the app was initialized. So I set it in app.js, before initializing everything.
I don't find it clean but at least it works. If someone gets the same issue, here is app.js:
import Vue from 'vue';
import Vuetify from 'vuetify';
import VueInternationalization from 'vue-i18n';
import Locale from './vue-i18n-locales.generated.js';
Vue.use(Vuetify);
Vue.use(VueInternationalization);
require('./bootstrap');
window.Vue = require('vue');
var App = Vue.component('app', require('./App.vue').default, {
name: 'app'
});
var Home = Vue.component('home', require('./components/home/HomeComponent.vue').default);
//and all other components
let lang=localStorage.Lang;
if(lang==null){ //I really don't like this part though... if tehre is nothing in the local storage, I need to get the language in the DB
axios.get('/getlang/').then(
response => {
lang = response.data;
init();
}
);
}
else{
init();
}
function init(){
let i18n = new VueInternationalization({
locale: lang,
messages: Locale
});
const app = new Vue({
el: '#app',
i18n,
components:{app:App, home:Home} //and all other omponents
});
}