Multi Language

Introduction

Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.

Typically, translation strings are stored in files within the lang directory. Within this directory, there should be a subdirectory for each language supported by your application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages:

All language files return an array of keyed strings. For example:

<?php

// lang/en/messages.php
    
return [
    'welcome' => 'Welcome to velzon laravel!',
];
Retrieving Translation Strings

You may retrieve translation strings from your language files using the __ helper function. If you are using "short keys" to define your translation strings, you should pass the file that contains the key and the key itself to the __ function using "dot" syntax. For example, let's retrieve the welcome translation string from the lang/en/translation.php language file:

echo __('translation.welcome');

If you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive:

{{ __('translation.welcome') }}
@lang('translation.welcome')

Localization in Velzon Laravel

In Velzon laravel, We provide a dropdown to switch language you can find it in the top-bar. How does it work? When we select a language from dropdown-menu we call a Route which calls a controller's function which then put selected language in session. We have created a middleware that sets the localization value from the session variable. It sounds a little messy. Let's find out how to do it.

Use the below code in HomeController file in App/Http/Controllers.

 public function lang($locale)
{
    if ($locale) {
        App::setLocale($locale);
        Session::put('lang', $locale);
        Session::save();
        return redirect()->back()->with('locale', $locale);
    } else {
        return redirect()->back();
    }
}

We have to define Route for language switching in routes/web.php file.

<?php
use App\Http\Controllers\HomeController;
// locale Route
Route::get('index/{locale}', [App\Http\Controllers\HomeController::class, 'lang']);

Now we need a middleware to set app()->setLocale() variable gloabaly. Run below cammand to create a middleware.

php artisan make:middleware Localization

You can find this middleware in App\Http\Middleware

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\App;

class Localization
{
    /**
        * Handle an incoming request.
        *
        * @param  \Illuminate\Http\Request  $request
        * @param  \Closure  $next
        * @return mixed
        */
    public function handle(Request $request, Closure $next)
    {
        /* Set new lang with the use of session */
        if (session()->has('lang')) {
            App::setLocale(session()->get('lang'));
        }
        return $next($request);
    }
}

You must have to mention middleware in the App\Http\kernel.php file. Use the \App\Http\Middleware\LocaleMiddleware::class, line in kernel.php file.

protected $middlewareGroups = [
'web' => [

    \App\Http\Middleware\Localization::class,
],

'api' => [
    'throttle:api',
    \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

];

Now we have to set the view. We provide language switch dropdown in topbar.blade.php.

<div class="dropdown ms-1 topbar-head-dropdown header-item">
    <button type="button" class="btn btn-icon btn-topbar btn-ghost-secondary rounded-circle"
        data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        @switch(Session::get('lang'))
        @case('ru')
            <img src="{{ URL::asset('/build/images/flags/russia.svg') }}" class="rounded" alt="Header Language"
                height="20">
        @break
        @case('it')
            <img src="{{ URL::asset('/build/images/flags/italy.svg') }}" class="rounded" alt="Header Language"
                height="20">
        @break
        @default
            <img src="{{ URL::asset('/build/images/flags/us.svg') }}" class="rounded" alt="Header Language" height="20">
    @endswitch
    </button>
    <div class="dropdown-menu dropdown-menu-end">

        <!-- item-->
        <a href="{{ url('index/en') }}" class="dropdown-item notify-item language py-2" data-lang="en"
            title="English">
            <img src="{{ URL::asset('build/images/flags/us.svg') }}" alt="user-image" class="me-2 rounded" height="20">
            <span class="align-middle">English</span>
        </a>

        <!-- item-->
        <a href="{{ url('index/sp') }}" class="dropdown-item notify-item language" data-lang="sp"
            title="Spanish">
            <img src="{{ URL::asset('build/images/flags/spain.svg') }}" alt="user-image" class="me-2 rounded" height="20">
            <span class="align-middle">Española</span>
        </a>
    </div>
</div>

Include the newly created switcher into the “welcome” view:

welcome.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>  
        <title> @lang('translation.welcome')</title>
    </head>
</html>
    
Resources/views/layouts

sidebar.blade.php

<li class="nav-item">
<a href="#sidebarCRM" class="nav-link" data-bs-toggle="collapse" role="button"
    aria-expanded="false" aria-controls="sidebarCRM" >@lang('translation.crm')
</a>
<div class="collapse menu-dropdown" id="sidebarCRM">
    <ul class="nav nav-sm flex-column">
        <li class="nav-item">
            <a href="apps-crm-contacts" class="nav-link" >@lang('translation.contacts')</a>
        </li>
        <li class="nav-item">
            <a href="apps-crm-companies" class="nav-link" >@lang('translation.companies')</a>
        </li>
        <li class="nav-item">
            <a href="apps-crm-deals" class="nav-link" >@lang('translation.deals')</a>
        </li>
        <li class="nav-item">
            <a href="apps-crm-leads" class="nav-link" >@lang('translation.leads')</a>
        </li>
    </ul>
</div>
</li>

Multi Language Settings

Let's add the French language.
  • To add a new language in whole template first we need to create a translation.php file in lang which return an array with key and value pair.
  • Now you need to add the language in the resources/view/layouts/top-bar.blade.php file. add the "case" condition as below code and make sure to add the french.jpg file in the public/build/images/flags folder.
    @case('ru'){
        document.getElementById("header-lang-img").src = "/build/images/flags/french.jpg";
        <img src="{{ URL::asset('/build/images/flags/french.svg')">
        
    }
  • You can simply use @lang attributes in the HTML tag to convert the language text. Example: <a href="#">@lang('translation.title')</a>
  • Add the below dropdown in the resources/view/layouts/topbar.blade.php file in the language dropdown.

    <a href="javascript:void(0);" class="dropdown-item notify-item language" data-lang="sp" title="Spanish">
        <img src="{{ URL::asset('/build/images/flags/french.jpg') }}" alt="user-image" class="me-2 rounded" height="18">
        <span class="align-middle">French</span>
    </a>