Last active
November 9, 2022 04:00
-
-
Save sm-jahangir/418ac6b1ca4aefa61fc9da56d5cbafba to your computer and use it in GitHub Desktop.
change laravel language system this method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. create language file in lang folder | |
en.json, jpn.json, ko.json, hi.json.. | |
jpn.json->{"Log in": "ログイン", "Register": "登録", etc...} | |
2. create controller and middleware for localization | |
-> $ php artisan make:middleware Localization | |
-> $ php artisan make:controller LocalizationController | |
3. declare localization middleware in kernel.php | |
protected $middlewareGroups = [ | |
'web' => [ | |
\App\Http\Middleware\EncryptCookies::class, | |
... | |
Localization::class, | |
], | |
] | |
4. create route for localization. | |
Route::get('/lang/{locale}', [\App\Http\Controllers\LocalizationController::class,'lang_change'])->name('lang.change'); | |
5. In LocalizationController.php | |
public function lang_change($locale){ | |
Session::put("locale",$locale); | |
return redirect()->back(); | |
} | |
6. In localization.php <- middleware file | |
-> public function handle(Request $request, Closure $next) | |
{ | |
if(Session::has("locale")) | |
App::setLocale(Session::get("locale")); | |
else | |
App::setLocale(config("app.locale")); | |
return $next($request); } | |
} | |
7. use in blade | |
{{__('Log in')}} | |
{{__('Register')}} | |
8. choose languages from blade | |
<div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown"> | |
<ul class="list-group list"> | |
<li class="list-group-item border-0"> | |
<a href="{{route('lang.change','en')}}">English</a> | |
</li> | |
<li class="list-group-item border-0"> | |
<a href="{{route('lang.change','jpn')}}">Japanese</a> | |
</li> | |
<li class="list-group-item border-0"> | |
<a href="{{route('lang.change','ko')}}">Korea</a> | |
</li> | |
<li class="list-group-item border-0"> | |
<a href="{{route('lang.change','hi')}}">Hindi</a> | |
</li> | |
</ul> | |
</div> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment