Mastering Localization in Laravel: A Complete Guide

Mastering Laravel Localization: A Step-by-Step Guide

Introduction:

Localization, the process of adapting your application to different languages and regions, is essential for reaching a global audience. In Laravel, the process of localization is made seamless with built-in features that allow you to translate your application into multiple languages effortlessly. In this guide, we’ll walk through the steps of setting up localization in Laravel, from language files to dynamic language switching.

Language Files:

We start by creating language files for English and French in resources/lang/en/messages.php and resources/lang/fr/messages.php respectively. These files contain key-value pairs for each localized string used in the application.

// resources/lang/en/messages.php
return [
    'title' => 'Welcome to My Website',
    'welcome' => 'Welcome to our website!',
    'about' => 'Learn more about us.',
    'contact' => 'Contact us for more information.',
];
// resources/lang/fr/messages.php
return [
    'title' => 'Bienvenue sur Mon Site Web',
    'welcome' => 'Bienvenue sur notre site Web!',
    'about' => 'Apprenez-en davantage sur nous.',
    'contact' => 'Contactez-nous pour plus d\'informations.',
];

Environment Variables:

Set the application’s locale in the .env file to specify the default language. This setting ensures consistency across different environments.

# .env
APP_LOCALE=en

Configuration Files:

Update the config/app.php file to set the default locale to English. This ensures that English is used as the default language when the application loads.

// config/app.php
'locale' => env('APP_LOCALE', 'en'),

View Files:

Update the blade templates to utilize the localization keys defined in the language files. This ensures that the correct language strings are displayed to users based on their language preference.

Update your views layout file for the language switcher option layouts/app.blade.php templates to use the localization keys.

// resources/views/layout/app.blade.php

<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{{ __('messages.title') }}</title>
</head>
<body>
    <header>
        <ul>
            <li><a href="#" onclick="changeLocale('en')">English</a></li>
            <li><a href="#" onclick="changeLocale('fr')">French</a></li>
        </ul>
    </header>
    <div>
        @yield('content')
    </div>
    <script src="{{ asset('js/app.js') }}"></script>
</body>
</html>

Create Blade Templates: Create blade templates for your views, for example, resources/views/home.blade.php

@extends('layouts.app')

@section('content')
    <h1>{{ __('messages.welcome') }}</h1>
    <p>{{ __('messages.about') }}</p>
    <p>{{ __('messages.contact') }}</p>
@endsection

JavaScript:

Create a JavaScript file to handle changing the locale (public/js/app.js ):

function changeLocale(locale) {
    fetch('/change-locale/' + locale, {
        method: 'POST',
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        },
        body: JSON.stringify({ locale: locale })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            window.location.reload();
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
}

Helpers or Traits:

Create a helper function or trait to handle changing the locale dynamically. This trait allows users to switch between English and French languages seamlessly.

// app/Traits/LocalizesApp.php
namespace App\Traits;

use Illuminate\Support\Facades\App;

trait LocalizesApp
{
    public function updateLocale($locale)
    {
        App::setLocale($locale);
        session()->put('locale', $locale);
    }
}

Define the LocaleController:

Define the LocaleController to handle the localization logic.

// app/Http/Controllers/LocaleController.php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Traits\LocalizesApp;

class LocaleController extends Controller
{
    use LocalizesApp;

    public function changeLocale($locale)
    {
        // Call the changeLocale method from the LocalizesApp trait
        $this->updateLocale($locale);
        return redirect()->back();
    }
}

Routes:

Define a route to handle changing the locale (routes/web.php):

Route::post('/change-locale/{locale}', 'LocaleController@changeLocale')->name('change.locale');

You can get more details about this topic from here.

To get to know more about Laravel, you can check these articles too:

  1. Laravel Eloquent ORM: A Beginner’s Guide
  2. Laravel Blade Templates: Mastering the Basics

Conclusion:

By implementing language localization in Laravel, you can create multilingual websites that cater to a global audience. This feature enhances user experience and accessibility, making your website more inclusive and user-friendly.

Please follow and like us:

Related Posts

1 Comment

Leave a Reply

Share