How to Make Laravel 9 Website Multilingual
Today's tutorial will show you how to make your Laravel 9 website Multilingual, we will see how to create the database and add routes, and toggle the languages.
Create the database
First, let's create the database and add columns like below.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->id();
$table->string('title_fr');
$table->string('title_en');
$table->string('slug');
$table->text('body_fr');
$table->text('body_en');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
};
Add changeLang function
Inside your HomeController add the changeLang function.
public function changeLang($lang){
session()->forget('lang');
session()->put('lang', $lang);
return redirect()->back();
}
Create the route
Inside the web.php file, we create the route to toggle the languages.
Route::get('change/lang/{lang}', [HomeController::class, 'changeLang'])
->name('change.lang');
Add the menu item
Inside the navbar, we add the menu item to change the language.
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="fas fa-language"></i> Languages
</a>
<ul class="dropdown-menu">
<li><a class="dropdown-item" href="{{route('change.lang','en')}}">En</a></li>
<li><a class="dropdown-item" href="{{route('change.lang','fr')}}">Fr</a></li>
</ul>
</li>
Display content based on the selected language
So when the user changes the language we can display the content based on the selected language like below.
@extends('layouts.main')
@section('title')
Home
@endsection
@section('content')
<div class="row my-5">
<div class="col-md-12">
<div class="card p-4">
<div class="row">
@foreach ($posts as $post)
<div class="col-md-4 mb-2">
<div class="card h-100">
<div class="card-body">
<div class="card-title fw-bold">
@if(session()->get('lang') === 'fr')
{{$post->title_fr}}
@else
{{$post->title_en}}
@endif
</div>
<p class="card-text">
@if(session()->get('lang') === 'fr')
{{ Str::limit($post->body_fr, 100) }}
@else
{{ Str::limit($post->body_en, 100) }}
@endif
</p>
<a href="{{route('posts.show', $post)}}" class="btn btn-primary">
<i class="fas fa-eye"></i>
@if(session()->get('lang') === 'fr')
Voir
@else
View
@endif
</a>
</div>
</div>
</div>
@endforeach
</div>
<div class="card-footer bg-white">
<div class="d-flex justify-content-center">
{{$posts->links()}}
</div>
</div>
</div>
</div>
</div>
@endsection