How to make translation for Laravel Vue JS using Lang | Laravel Localization for Vue

By Ved Prakash N | Jun 13, 2022 | Laravel
Share : Whatsapp

https://www.fundaofwebit.com/post/how-to-make-translation-for-laravel-vue-js

How to make translation in Laravel Vue JS using Lang.js


In this article, we will be learning about how to do the translation for vue js in laravel using Lang package.

"Lang.js" is a package - Laravel Translator Class in Javascript.  Click Here for Doc


Step 1: Install Lang.js Package

$ npm install lang.js


Step 2: Paste the below code in your blade.php file. (app.blade.php)

<script>
    window.default_locale = "{{ app()->getLocale() }}"; //current language set by default
    window.fallback_locale = "{{ config('app.fallback_locale') }}";
</script>


Step 3: Go to app.js file in following path - resources/js/app.js

import Lang from 'lang.js';
const default_locale = window.default_language;
const fallback_locale = window.fallback_locale;

import allLang from '../lang/lang.json';
var source = allLang;

Vue.prototype.trans = new Lang({
    messages: source,
    locale: default_locale,
    fallback: fallback_locale
});


Step 4: Create a file named "lang.json" in the following path - resources/lang/lang.json

In this file, we are going to write the translation (English, Esperanto, Arabic) as given below: 

{
    "en.lang": {
        "Home":"Home",
        "About Us":"About Us",
        "Contact Us":"Contact Us",
        "Blog":"Blog"
    },
    "es.lang": {
        "Home":"Hejmo",
        "About Us":"Pri ni",
        "Contact Us":"Kontaktu Nin",
        "Blog":"Blogo"
    },
    "ar.lang": {
        "Home":"مسكن",
        "About Us":"معلومات عنا",
        "Contact Us":"اتصل بنا",
        "Blog":"مقالات"
    }
}


Step 5: To translate, use the below syntax in Vue Component:

Syntax: {{ trans.get('lang.FINANCE CALCULATOR') }}
<ul>
    <li>{{ trans.get('lang.Home') }}</li>
    <li>{{ trans.get('lang.About Us') }}</li>
    <li>{{ trans.get('lang.Contact Us') }}</li>
</ul>

That's all for the Vue Setup. 


If you have not done with the language Switch Routes in Laravel please continue below to setup laravel locale. 

Now, here we are going to setup the Laravel Locale Translation.

Step 1: go to app.php file in the following path - config/app.php and paste the below code

'languages' => [
    'en' => 'English',
    'ar' => 'Arabic',
],


Step 2: lets create a dropdown using bootstrap 5 and get the languages from config/app.php file and paste in blade.php file.

<div class="text-end">
    @if(count(config('app.languages')) > 1)
        <div class="dropdown">
            <a class="btn dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" v-pre>
                {{ strtoupper(app()->getLocale()) }}
            </a>
            <div class="dropdown-menu dropdown-menu-end">
                @foreach(config('app.languages') as $langLocale => $langName)
                    <a class="dropdown-item" href="{{ url()->current() }}?change_language={{ $langLocale }}">{{ strtoupper($langLocale) }} ({{ $langName }})</a>
                @endforeach
            </div>
        </div>
    @endif
</div>


Step 3: Create a middleware

$ php artisan make:middleware Localization


go to the Localization middleware at the following path: app/Http/Middleware/Localization.php and paste the below code:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class Localization
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse)  $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        $languages = array_keys(config('app.languages'));
        $route = $request->route();

        if (request('change_language')) {
            session()->put('language', request('change_language'));
            $language = request('change_language');
            if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language)
            {
                $route->parameters['locale'] = $language;

                if (in_array($language, $languages)) {
                    app()->setLocale($language);
                }

                return redirect(route($route->getName(), $route->parameters));
            }
        } elseif (session('language')) {
            $language = session('language');

            if (array_key_exists('locale', $route->parameters) && $route->parameters['locale'] != $language && in_array($route->parameters['locale'], $languages))
            {
                $language = $route->parameters['locale'];
                session()->put('language', $language);
            }
        } elseif (config('app.locale')) {
            $language = config('app.locale');
        }

        if (isset($language) && in_array($language, $languages)) {
            app()->setLocale($language);
        }

        return $next($request);
    }
}

Register this above Localization Middleware in kernel.php as given below:

protected $middlewareGroups = [
    'web' => [
        ...
        \App\Http\Middleware\Localization::class,
    ],
];


That's all guys, its setup now.


To display the translation in blade.php files.

{{ __('Home') }}

and its translation will be written directly in  each json files in following path:
1. resources\lang\en.json
Eg: 

{
    "Home":"Home",
    "About Us":"About Us",
    "Contact Us":"Contact Us",
    "Blog":"Blog"
}

2. resources\lang\ar.json

Eg:

{
    "Home":"مسكن",
    "About Us":"معلومات عنا",
    "Contact Us":"اتصل بنا",
    "Blog":"مقالات"
}


Thanks for reading.