Laravel Localization(trans Helper) Tutorial Example
Hello Friends,
This post is focused on laravel localization tutorial. This article will give you a simple example of laravel localization example. This article will give you a simple example of laravel trans tutorial. you can understand a concept of laravel trans helper example. So, let's follow a few steps to create an example of laravel trans function.
In this example, we will create three languages English, Spanish and French website with translation. we will use laravel localization to add a translation for label. Then we will create middleware to manage dynamic language. We will create one blade file with a dropdown where we can select a language and it will work dynamically. so let's see the below steps:
So, let's follow few step to adding multi language support in laravel.
Step 1: Install Laravel
This is optional; 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: Create Lang Files
In this step, we simply need to create following folders and files for english, france and spanish language files in lang folder.
You need to run following commands for lang files:
php artisan lang:publish
let's create files as bellow listed:
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
<?php
return [
'title' => "Il s'agit du titre en langue espagnole.",
];
Step 3: Create Routes
In this step, we will create two routes one for display dashboard page with language dropdown and another for you can change language logic.
so add bellow routes.
routes/web.php
<?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');
Step 4: Create LangController Controller
In this point, now we should create new controller as LangController. this controller will manage layout and change language dynamically logic, so put bellow content in controller file:
app/Http/Controllers/LangController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\View\View;
use Illuminate\Http\RedirectResponse;
use App;
class LangController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index(): View
{
return view('lang');
}
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function change(Request $request): RedirectResponse
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
return redirect()->back();
}
}
Step 5: Create View
In Last step, let's create lang.blade.php(resources/views/lang.blade.php) for layout and we will write design code here and put following code:
resources/views/lang.blade.php
<!DOCTYPE html>
<html>
<head>
<title>How to Create Multi Language Website in Laravel - ItSolutionStuff.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 - ItSolutionStuff.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>
Step 6: Create Middleware
In this file we need to create one middleware that will manage dynamic language that we selected on dropdown. so let's create middleware using bellow language.
php artisan make:middleware LanguageManager
Now you have to update middleware file like bellow:
app/Http/Middleware/LanguageManager.php
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
use App;
class LanguageManager
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (session()->has('locale')) {
App::setLocale(session()->get('locale'));
}
return $next($request);
}
}
Now we need to register it to kernel file. so let's add it as bellow:
app/Http/Kernel.php
<?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 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/lang/home
English Language:
Franch Language:
Spanish Language:
I hope it can help you...
Hardik Savani
I'm a full-stack developer, entrepreneur and owner of ItSolutionstuff.com. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.
We are Recommending you
- Laravel Install Tailwind CSS Example
- How to Get Request Method in Laravel?
- How to Deploy Project with Laravel Vapor?
- Laravel Migration Enum Default Value Example
- How to Add Custom env Variables in Laravel?
- Laravel Collection Sum Column Example
- Laravel Phone Number Verification using Firebase Example
- How to Get Specific Attributes from Laravel Collection?
- Laravel Google Chart Example Tutorial
- Laravel Eloquent Order By Query Example
- Laravel Export to PDF using Maatwebsite Example
- Laravel XSS Protection Middleware Example
- How to Get Difference Between Two Dates in Laravel?