Laravel 11 Localization | Create Multi Language in Laravel 11

By Hardik Savani September 4, 2024 Category : Laravel

In this tutorial, I will show you how to make multi language support using localization in laravel 11 application.

What is Laravel Localization?

Laravel Localization is a feature that allows you to create multilingual websites. It helps you translate your application's content into different languages. With Laravel Localization, you can store translations in language files and switch between languages easily. This is useful if you want your website to reach users who speak different languages, offering a more personalized experience. It's built into Laravel, making it simple to use.

In this example, we will first install Laravel Breeze for authentication. Next, we will set up the language files for localization. We will create three languages: English ("en"), Italian ("it"), and French ("fr"), each with their own messages. Then, we will add a dropdown menu on the navigation bar where users can pick a language. When a user selects a language, the labels on the page will change accordingly. Let's go through the steps one by one.

laravel 11 multi language

Step for Multi Language in Laravel 11

  • Step 1: Install Laravel 11
  • Step 2: Install Laravel Breeze
  • Step 3: Create Migration and Update Model
  • Step 4: Create UserAccess Middleware
  • Step 5: Create Routes
  • Step 6: Update Controller
  • Step 7: Create Blade Files
  • Step 8: Update LoginController File
  • Step 9: Create User Seeder
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Laravel Breeze

Now, in this step, we will create an auth scaffold command to generate login, register, and dashboard functionalities using breeze. So, run the following commands:

Laravel 11 Breeze Package:

composer require laravel/breeze --dev

Generate Auth:

php artisan breeze:install

npm install

npm run build

Step 3: Define Language Messages

In this step, we will define all three language messages.

so, first we need to run following command to use localization:

php artisan lang:publish

now, let's define messages for en, it and fr language:

lang/en/messages.php

<?php

return [
    "users" => "Users",
    "users_list" => "Users Listing",
    "dashboard" => "Dashboard",
    "dashboard_message" => "You're logged in!"
];

lang/fr/messages.php

<?php

return [
    "users" => "Utilisatrices",
    "users_list" => "Liste des utilisateurs",
    "dashboard" => "Tableau de bord",
    "dashboard_message" => "Vous êtes connecté!"
];

lang/it/messages.php

<?php

return [
    "users" => "Utenti",
    "users_list" => "Elenco degli utenti",
    "dashboard" => "Pannello di controllo",
    "dashboard_message" => "Hai effettuato l'accesso!"
];

Step 4: Create SetLocale Middleware

In this step, we need to create a middleware to set current locale language, so let's create middleware using the below command.

php artisan make:middleware SetLocale

app/Http/Middleware/SetLocale.php

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use Illuminate\Support\Facades\App;

class SetLocale
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if($request->session()->has('locale')){
            App::setLocale($request->session()->get('locale', 'en'));
        }

        return $next($request);
    }
}

Next, we need to register the SetLocale middleware to the app.php file.

bootstrap/app.php

<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->web(append: [
            SetLocale::class
        ]);
    })
    ->withExceptions(function (Exceptions $exceptions) {
        //
    })->create();

Step 5: Create Routes

Here, We will add following routes group where you can create new routes for users and change language. let's update code:

routes/web.php

<?php

use App\Http\Controllers\ProfileController;
use App\Http\Controllers\UserController;
use App\Http\Controllers\LanguageController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');
});

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth', 'verified'])->name('dashboard');

Route::middleware('auth')->group(function () {
    Route::get('/profile', [ProfileController::class, 'edit'])->name('profile.edit');
    Route::patch('/profile', [ProfileController::class, 'update'])->name('profile.update');
    Route::delete('/profile', [ProfileController::class, 'destroy'])->name('profile.destroy');

    Route::get('lang', [LanguageController::class, 'change'])->name("change.lang");

    Route::get('users', [UserController::class, 'index'])->name('users.index');
});

require __DIR__.'/auth.php';

Step 6: Create Controller

Here, we will create new LanguageController and UserController, then update both controller file. So let's add them as follows:

first, run the following commands to create controller file:

php artisan make:controller LanguageController

php artisan make:controller UserController

app/Http/Controllers/LanguageController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class LanguageController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function change(Request $request)
    {
        $lang = $request->lang;

        if (!in_array($lang, ['en', 'it', 'fr'])) {
            abort(400);
        }

        Session::put('locale', $lang);

        return redirect()->back();
    }
}

app/Http/Controllers/UserController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        return view("users");
    }
}

Step 7: Create & Update Blade Files

In this step, we need to create a new blade file for the admin and update the blade files. So let's change it.

resources/views/layouts/navigation.blade.php

...
<!-- Settings Dropdown -->
<div class="hidden sm:flex sm:items-center sm:ms-6">
    <x-dropdown align="right" width="48">
        <x-slot name="trigger">
            <button class="inline-flex items-center px-3 py-2 border border-transparent text-sm leading-4 font-medium rounded-md text-gray-500 dark:text-gray-400 bg-white dark:bg-gray-800 hover:text-gray-700 dark:hover:text-gray-300 focus:outline-none transition ease-in-out duration-150">
                @php($languages = ['en' => 'English', 'fr' => 'French', 'it' => 'Italian'])
                <div>Language: {{ $languages[Session::get('locale', 'en')] }}</div>

                <div class="ms-1">
                    <svg class="fill-current h-4 w-4" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
                        <path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
                    </svg>
                </div>
            </button>
        </x-slot>

        <x-slot name="content">
            <x-dropdown-link :href="route('change.lang', ['lang' => 'en'])">
                English
            </x-dropdown-link>
            <x-dropdown-link :href="route('change.lang', ['lang' => 'fr'])">
                French
            </x-dropdown-link>
            <x-dropdown-link :href="route('change.lang', ['lang' => 'it'])">
                Italian
            </x-dropdown-link>
        </x-slot>
    </x-dropdown>
    ...
</div>

resources/views/dashboard.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('messages.dashboard') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    {{ __("messages.dashboard_message") }}
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

resources/views/users.blade.php

<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-xl text-gray-800 dark:text-gray-200 leading-tight">
            {{ __('messages.users') }}
        </h2>
    </x-slot>

    <div class="py-12">
        <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-6 text-gray-900 dark:text-gray-100">
                    {{ __('messages.users_list') }}
                </div>
            </div>
        </div>
    </div>
</x-app-layout>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/

Now, you can register and change the language. it will work.

Output:

I hope it can help you...

Shares