To change laravel locale dynamically we can apply different ways.Today I will teach you very easily
and professional way that I use to follow in all my laravel projects.
Step: 1
Define middleware
you can see I have defined Localization middleware.Which will check locale variable in session
and on each request it will set application locale variable.
Step: 2
Include middle in kernal.php php
\App\Http\Middleware\Localization::class,
step: 3
Set locale using session variable.For example I have used in web.php
Here you can see i am setting locale variable in two languages english and french.
So requests changeLocale/en and So changeLocale/fr will set locale value.
step: 4
html code that will allow use to change language and hit above get request.
<li class="eborder-top">
@if( \Session::get('locale') == "fr" )
<a href="{{ url('/changeLocale/en') }}">
<i class="fa fa-key" aria-hidden="true"></i> English
</a>
@else
<a href="{{ url('/changeLocale/fr') }}">
<i class="fa fa-key" aria-hidden="true"></i> French
</a>
@endif
</li>
Above will check locale key in session and based on that it will run the routed and after
running the route it will set the session key locale value.
For any questions or understanding please do contact !
No comments:
Post a Comment