Make a multi language website using the Laravel 9 apps; We will learn how to develop a multi language website using Laravel 9 apps with this guide.

Table of Contents

  1. Install Laravel
  2. Create Lang Files
  3. Create Routes
  4. Create Controller
  5. Create View
  6. Create Middleware
  7. Start Laravel App

Install Laravel

Use the command prompt to run the following command to install the Laravel app on your computer:

composer create-project laravel/laravel example-app

Create Lang Files

Create the following files and folders in the lang folder for the languages of English, French, and Spanish:

resources/lang/en/messages.php

<?php
return [
    'title' => 'This is English Language Title.',
];

resources/lang/fr/messages.php

<?php
return [
    'title' => 'Ceci est le titre fr langue anglaise.',
resources/lang/sp/messages.php

];

resources/lang/sp/messages.php

<?php
return [
    'title' => "Il s'agit du titre en langue espagnole.",
];

Create Routes

Open web.php in the routes directory. Create two routes by doing the following: one route will display the dashboard page with a language dropdown; the second way will allow you to modify the language logic.

<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\LangController;
 

/*
 
|--------------------------------------------------------------------------
 
| Web Routes
 
|--------------------------------------------------------------------------
 
|
 
| Here is where you can register web routes for your application. These
 
| routes are loaded by the RouteServiceProvider within a group which
 
| contains the "web" middleware group. Now create something great!
 
|
 
*/
  
Route::get('lang/home', [LangController::class, 'index']);
 
Route::get('lang/change', [LangController::class, 'change'])->name('changeLang');

Create LangController Controller

Use the command prompt to create a LangController file by entering the following command:

php artisan make:controller LangController

then open the LangController.php file by going to app/http/controllers directory. Add the subsequent code after that:

<?php
 
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App;

class LangController extends Controller
{
     /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
    */
    public function index()
    {
        return view('lang');
    }
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
    */
    public function change(Request $request)
    {
        App::setLocale($request->lang);
        session()->put('locale', $request->lang);
        return redirect()->back();
    }
}

Create View

Create the lang.blade.php file by going to resources/views directory. Additionally, add the following code to the file lang.blade.php:

<!DOCTYPE html>
<html>
<head>
    <title>How to Create Multi Language Website in Laravel - CodeSolutionStuff.com</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="//netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h1>How to Create Multi Language Website in Laravel - CodeSolutionStuff.com</h1>
        <div class="row">
            <div class="col-md-2 col-md-offset-6 text-right">
                <strong>Select Language: </strong>
            </div>
            <div class="col-md-4">
                <select class="form-control changeLang">
                    <option value="en" {{ session()->get('locale') == 'en' ? 'selected' : '' }}>English</option>
                    <option value="fr" {{ session()->get('locale') == 'fr' ? 'selected' : '' }}>France</option>
                    <option value="sp" {{ session()->get('locale') == 'sp' ? 'selected' : '' }}>Spanish</option>
                </select>
            </div>
        </div>
        <h1>{{ __('messages.title') }}</h1>
    </div>
</body>
<script type="text/javascript">
    var url = "{{ route('changeLang') }}";
    $(".changeLang").change(function(){
        window.location.href = url + "?lang="+ $(this).val();
    });
</script>
</html>Create Middleware

Create Middleware

To establish a middleware that will manage the dynamic language we choose from the selection, run the following command at the command prompt:

php artisan make:middleware LanguageManager

Open the LanguageManager.php file by going to the app/Http/Middleware/ directory. and incorporate the subsequent code into it:

<?php
namespace App\Http\Middleware;
use Closure;
use App;
class LanguageManager
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (session()->has('locale')) {
            App::setLocale(session()->get('locale'));
        }
        return $next($request);
    }
}

Open the Kernel.php file by going to the app/Http/ directory. Middleware for registering is as follows:

<?php
namespace App\Http;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
    ....
    /**
     * The application's route middleware groups.
     *
     * @var array
     */
    protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\LanguageManager::class,
        ],
        'api' => [
            'throttle:60,1',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],
    ];
    ...

Start Laravel App

Run the following command at a command prompt to launch the Larave app:

php artisan serve

I hope Laravel 9 Create Multi Language Website Example Tutorial blog can help you


Recommended Posts

View All

Laravel Where Clause with MySQL Function Example


laravel eloquent where year,laravel eloquent mysql functions,laravel eloquent where clause mysql,mysql function mysql laravel

Sentiment Analysis in Laravel with TextBlob


Sentiment analysis is a popular technique used in natural language processing to determine the overall sentiment or emotional tone of a piece of text.

Most Important Array Methods in JavaScript


Learn the most important array methods in JavaScript, including push, pop, shift, unshift, forEach, map, filter, reduce, and find. Improve your coding...

Laravel 9 Autocomplete Search using Typeahead JS Tutorial


Laravel 8 autocomplete search using Typehead JS from MySQL database example

Laravel 9 generate RSS Feed Tutorial With Example


Learn how to generate RSS feeds in Laravel 9 with our easy-to-follow tutorial. Get step-by-step instructions and real-world examples. Start today!