Laravel Localization: Step By Step Guide | Language Translation


                                             Localization In Laravel 8:



 Localization:

   Laravel's localization features provide a convenient way to retrieve strings in various languages, allowing you to easily support multiple languages within your application.


Laravel provides two ways to manage translation strings. First, language strings may be stored in files within the resources/lang directory. Within this directory, there may be subdirectories for each language supported by the application. This is the approach Laravel uses to manage translation strings for built-in Laravel features such as validation error messages





Step1: Create Blade File  for Language Menu:

  Create  Language Blade  file in Views:

ProjectName/resources/views/language/language_switcher.blade.php 

<div class=" " style="">
<div class="">
<div class="">
<button type="button" aria-label="Close" class="close lan_close"></button>
<div>
@foreach($availlocales as $locale_name => $availlocale)
@if($availlocale === $current_locale)
<div class="radio-btn radio_button active language_change"
data-link="{{url('/lang',$availlocale)}}">
<span><span ></span></span>
<div>{{ $locale_name }}</div>
</div>
@else
<div class="radio-btn radio_button language_change"
data-link="{{url('/lang',$availlocale)}}">
<span><span ></span></span>
<div>{{ $locale_name }}</div>
</div>
@endif
@endforeach
</div>
</div>
</div>
</div>

<script>
$('body').on('click', '.language_change', function(){
var linkurl = $(this).attr('data-link');
window.location.href=linkurl;
});
</script>

<style>




.radio-btn {
display: flex !important;
-moz-justify-content: flex-start;
-ms-justify-content: flex-start;
justify-content: flex-start;
-ms-flex-pack: flex-start;
-moz-align-items: center;
-ms-align-items: center;
align-items: center;
font-weight: 400;
position: relative;
cursor: pointer;
}

.radio-btn:not(:last-of-type) {
margin-bottom: 20px;
}

.radio-btn.active span span {
background: #c51324;
}

.radio-btn span {
border: 1px solid #b5b5ba;
width: 20px;
height: 20px;
border-radius: 50%;
position: relative;
}

.radio-btn span span {
width: 10px;
height: 10px;
position: absolute;
transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
-moz-transform: translate(-50%, -50%);
-o-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
top: 50%;
left: 50%;
border: 0px;
}

.radio-btn div {
margin: auto auto auto 10px;
color: #b5b5ba;
font-size: 14px;
}
</style>



Step2: Send Language Menu details through  App Service Provider using Composer View:


When a view is rendered, callbacks or class methods are triggered, and these are known as view composers. A view composer can assist you in centralising logic if you have data that has to be tied to a view each time it is shown. When the same view is delivered by several routes or controllers in your application and requires a certain piece of data consistently, view composers could be especially helpful.

app/Providers/AppServiceProvider.php


<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use View;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}

/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
//
view()->composer('language.language_switcher',function($view){
$view->with('current_locale',app()->getLocale());
$view->with('availlocales',config('app.availlocales'));
});
}
}



Step3: Create Array of menu for Language from Config app.php:


'availlocales' =>[
'English' => 'en',
'French' => 'fr',
'Hindi' => 'hi',
'Tamil' => 'tam',
'Telugu' => 'tel',
'Kannada' => 'kan'
],


/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by the translation service provider. You are free to set this value
| to any of the locales which will be supported by the application.
|
*/

'locale' => 'en',

Step4: Create Route for  Language Translation:


Here we  getting Language  details from locale and Setting  Locale details  via Cookie:

Web.php


Route::get('/lang/{locale?}',function($locale=null){
if(isset($locale) && in_array($locale,config('app.availlocales'))){
//app()->setlocale($locale);
$duration= 2880;
Cookie::queue('locale', $locale, $duration);
}
return redirect()->back();
});



Step5: Creating Middle ware to Set Language Change Using App Locale Method:


Php artisan make:Middleware Localization



<?php

namespace App\Http\Middleware;

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

class Localizatiion
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure(\Illuminate\Http\Request):
(\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
* @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
*/
public function handle(Request $request, Closure $next)
{
if(Cookie::has('locale')){
App::setLocale(Cookie::get('locale'));
}
return $next($request);
}
}

Getting language details from Cookie and Change Locale Using App::SetLocale Method


Step6: Create Json File  in Lang

Path Where Json File has to be  Created:

ProjectName/resource/lang/tam.json

Similarly Create Json file for Other Languages:

ProjectName/resource/lang/hindi.json


{

"Name":"பெயர்",
"Product_id":"தயாரிப்பு_ஐடி",
"Product_name":"பொருளின் பெயர்",
"Quantity":"அளவு",
"Order":"ஆர்டர்",
"You are logged in!":"நீங்கள் உள்நுழைந்துள்ளீர்கள்!",
"Dashboard":"டாஷ்போர்டு",
"":""
}


Step7: Home Blade File to change language Details:

home.blade.php

In home blade Mention the Sentence with {{__('your content')}} to translate.

@extends('layouts.app')

@section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">{{ __('Dashboard') }}</div>

<div class="card-body">
@if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
@endif

{{ __('You are logged in!') }}

<div class="form-group">
<label for="Name">{{__('Name')}}</label>
<input type="text" class="form-control cls_name"
name="name" >
</div>
<div class="form-group " >
<meta name="csrf-token" content="{{ csrf_token() }}">
<label for="Name">{{__('Product_id')}}</label>
<input type="number"
class="form-control cls_product" name="Product_id" >
</div>
<div class="form-group">
<label for="Name">{{__('Product_name')}}</label>
<input type="text"
class="form-control cls_productname" name="Product_name" >
</div>
<div class="form-group">
<label for="Name">{{__('Quantity')}}</label>
<input type="number"
class="form-control cls_Quantity" name="Quantity" >
</div>
<button
class="btn btn-primary order_details">{{__('Order')}}</button>
<div>
</div>
</div>
</div>
</div>
</div>

<script>
</script>
@include('language.language_switcher')
@endsection



Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');


Language Change:





Refered Documents:

https://laravel.com/docs/8.x/localization



Comments

Popular posts from this blog

Laravel Notifications | Laravel Notify Using GMail to Send Invoice Details:

Laravel Socialite |Socialite: Creating a Social Login in Laravel Part 1