Search code examples
laravelvue.jsvuejs3laravel-9vue-i18n

How to use laravel-vue-i18n to change translations in laravel blades also?


Can anyone help me make translations working in laravel blades too? I need to change/translate the contents of the title and description meta depending on the language being switched.

This is how the language changes in Vue:

<template>
    <ul class='language-switcher'>
        <li :class="{'active': language === 'de'}">
            <a href='#' class='black-soft' @click="switchLanguageTo('de')">De</a>
        </li>
        <li :class="{'active': language === 'en'}">
            <a href='#' class='black-soft' @click="switchLanguageTo('en')">En</a>
        </li>
    </ul>
</template>

<script>
import {loadLanguageAsync} from "laravel-vue-i18n";

export default {
    name: "LanguageSwitcherComponent",
    data() {
        return {
            language: 'en',
        };
    },
    methods: {
        switchLanguageTo(lang) {
            // ...
            loadLanguageAsync(lang);
            // ...
        },
    },
}
</script>

In Vue, the translations work fine, but I need to translate title and description meta in index.balde.php as well.

<!DOCTYPE html>
<html lang="{{str_replace('_', '-', app()->getLocale())}}">
<head>
    <title>{{ __("Site Title") }}</title>
    <meta name="description" content="{{ __("Site Info") }}">
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="{{mix('css/app.css')}}">
</head>
<body>
<div id="app">
    <index-component/>
</div>
<script src="{{mix('js/app.js')}}"></script>
</body>
</html>

Also, this is how configured i18n in app.js:

import {i18nVue} from 'laravel-vue-i18n';
// ...
app.use(i18nVue, {
    lang: 'en',
    resolve: lang => import(`../../lang/${lang}.json`),
});

Thanks!


Solution

  • Save site language in cookies and in web.php set locale from cookies.

    Route::get('/{any}', function (Request $request) {
        // Set locale
        App::setLocale($request->cookie('site_language') ?: 'en');
        return view('index');
    })->where('any', '.*');
    

    Note: Maybe will need to add cookie name in app/Http/Middleware/EncryptCookies.php in $except list to get cookie from the $request successfully.