Localization in laravel Locale

Alam Riku
3 min readOct 11, 2020

at first create the json file ore a php file which will return a array of your choice language.

json format

these file should be save on resources > view > lang

file location

create a blade file

blade file to select the language

the outlook of the blade is

now have to ajax call when language option is change

now create the route

now create the controller

controller

we store the select langue option on session with key name ‘locale’

this part is important. we store the selected language on session but this session locale key value will be effective when browser get reload after the ajax call success location.reload().you will understand it very soon when I will explain the middleware part.

Now comes the Most beautiful and magical portion. But most complex

create a middleware Language php artisan make:middleware Language

Middleware
<?php

namespace
App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use Session;
use App;

class Language
{
/**
* 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')){
$locale = Session::get('locale');
}
elseif(env('DEFAULT_LANGUAGE') != null){
$locale = env('DEFAULT_LANGUAGE');
}
else{
$locale = 'en';
}

app()->setLocale($locale);
$request->session()->put('locale', $locale);
// dd(session('locale'));
return
$next($request);
}
}

write the above middleware code.

mistake can be done on app()->setLocale,and getting the $locale variable if you face problem have patient and try calmly you will get it.

now another crucial part is to register the middleware in Kernel.php

add the following line on web group notice its $middlewareGroups = [
‘web’

\App\Http\Middleware\Language::class,

now some explaination:

whenever we do a http request laravel bootstrap many important things.

one of them is web middleware group.

so when you clicked a language option its sent the request to our method and load the page. but firstly its goes to the middle first then go to the method.

request life cycle

so app()->setLocale($locale); set the value of the session to the locale config value.then goes to the method then ajax request is finished with success on success method page is reload using location.reload() after the page reload the language is change.

if we select english for local its store to the session value on the method and ajax page reload part do the job.

--

--

Alam Riku

I am a learner who dives into the ocean of knowledge realm.