How to Create Multilingual Website in Laravel 9?

Apr 29, 2022 . Admin



Hi Dev,

In this tutorial I will share with you how to create a multilingual website in laravel 9 application, I will show an example of laravel 9 in multiple languages.

Here, I will give you a full example of how to laravel 9 multilanguage with language dropdown or laravel 9 multiple language websites as below so follow my all steps.

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

Step 1: Download Laravel

Let us begin the tutorial by installing a new laravel application. if you have already created the project, then skip following step.

composer create-project laravel/laravel example-app
Step 2: Database Configuration

In second step, we will make database Configuration for example database name, username, password etc. So lets open .env file and fill all deatils like as bellow:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create Lang File

In this third step i will create three files in following folder for english,french,russian in lang folder.

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/ru/messages.php
<?php 

return [

    'title' => 'Это название на английском языке.'
    
];
Step 4: Create Route

In this step i will create two route one for display dashboard and second one is change language.

routes/web.php
<?php

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

/*
|--------------------------------------------------------------------------
| 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('/', [LanguageController::class, 'index'])->name('home');
Route::get('lan-change', [LanguageController::class, 'langChange'])->name('lan.change');
Step 5: Create Controller

In this step,we will create a controller. Use the below command for generate controller

php artisan make:controller LanguageController
app/Http/Controllers/LanguageController.php
<?php

namespace App\Http\Controllers;

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

class LanguageController extends Controller
{
    /**
     * Write Your Code.
     *
     * @return string
    */
    public function index()
    {
        return view('lang');
    }

    /**
     * Write Your Code...
     *
     * @return string
    */
    public function langChange(Request $request)
    {
        App::setLocale($request->lang);
        session()->put('locale',$request->lang);

        return redirect()->back();
    }
}
Step 6: Create Blade File

In this step, we will create a blade file name lang.blade.php bellow following path.

resources/views/lang.blade.php
<!DOCTYPE html>
<html>
<head>
    <title>How to Create Multilingual Website in Laravel 9?</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body class="bg-dark">
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-8 offset-2">
                <div class="card">
                    <div class="card-header">
                        <h5>How to Create Multilingual Website in Laravel 9 - <span class="text-primary">MyWebTuts.com</span></h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-3 col-md-offset-6 text-right">
                                <strong>Select Language: </strong>
                            </div>
                            <div class="col-md-9">
                                <select class="form-control changeLang">
                                    <option value="en" {{ session()->get('locale') == 'en' ? 'selected' : '' }}>English</option>
                                    <option value="fr" {{ session()->get('locale') == 'fr' ? 'selected' : '' }}>French</option>
                                    <option value="ru" {{ session()->get('locale') == 'ru' ? 'selected' : '' }}>Russian</option>
                                </select>
                            </div>
                        </div>
                        <h2 class="mt-4 text-center">{{ __('messages.title') }}</h2>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script>
    var url = "{{ route('lan.change') }}";

    $('.changeLang').change(function(){
        window.location.href = url + "?lang=" + $(this).val();
    });
</script>
</html>
Step 7: Create Middleware

In this step i will create one middleware for dynamically change language let's created below artisan command.

php artisan make:middleware LanguageManager
app/Http/Middleware/LanguageManager.php
<?php

namespace App\Http\Middleware;

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

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

So,now we need to register in kernel.php file so let's define.

<?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,
        ],
    ];
  
    ...
Run Laravel App:

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

php artisan serve

Now, you have to open web browser, type the given URL and view the app output:

http://localhost:8000/

It will help you...

#Laravel 9