Localization: Create Multi Language Website in Laravel 11

Hello, laravel web developers! In this article, we'll see how to create a multi-language website in laravel 11. In laravel 11, we'll use laravel localization to create a multi-language website. Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.

By default, the Laravel application skeleton does not include the lang directory. If you would like to customize Laravel's language files, you may publish them via the lang:publish Artisan command.

In this article, we'll install Laravel Breeze for authentication. Next, we'll set up the language files for localization. We'll create three languages: English ("en"), Chinese ("ch"), and Spanish ("sp"). Also, we'll add a dropdown menu on the navigation.

Localization: Create Multi Language Website in Laravel 11

Localization: Create Multi Language Website in Laravel 11

 

Step 1: Install Laravel 11 Application

In this step, we'll install the laravel 11 application using the following command.

composer create-project laravel/laravel laravel-11-example

 

Step 2: Install Laravel Breeze

 Then, install laravel breeze using the following command.

composer require laravel/breeze --dev

Next, we'll create laravel auth using the following command.

php artisan breeze:install

npm install

npm run build

 

Step 3: Publish the lang file

Then, we'll publish the lang file using the following command.

php artisan lang:publish

lang/en/messages.php

<?php

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

lang/ch/messages.php

return [
    "users" => "用户",
    "users_list" => "用户列表",
    "dashboard" => "仪表板",
    "dashboard_message" => "您已登录!"
];

lang/sp/messages.php

<?php

return [
    "users" => "Usuarios",
    "users_list" => "Lista de usuarios",
    "dashboard" => "Panel de control",
    "dashboard_message" => "¡Has iniciado sesión!"
];

 

Step 4: Create SetLocale Middleware

Next, we'll create a middleware using the following 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);
    }
}

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: Define Routes

Now, define the routes into the web.php file.

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');
});

 

Step 6: Create Controller

Next, create a controller using the following command.

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', 'ch', 'sp'])) {
            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 Blade Files

Then, create a blade file and create the dropdown for multi language website. When you change the language message will be shown in specific langage.

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', 'ch' => 'Chinese', 'sp' => 'Spanish'])
                <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' => 'ch'])">
                Chinese
            </x-dropdown-link>
            <x-dropdown-link :href="route('change.lang', ['lang' => 'sp'])">
                Spanish
            </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>

 

Step 8: Run the Laravel Application

Now, run the laravel 11 application using the following command.

php artisan serve

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS