Reputation: 65
I am working on Laravel localization. I have all done but facing issue. When I change language from dropdown page successfully transalated but language in ROUTE not change.
In web.php I have setup this,
Route::get('/', function () {
return redirect(app()->getLocale());
});
Route::get('language/change', [LocalizationController::class, 'changeLanguage'])->name('changeLang');
Route::group(
[
'prefix' => '{locale}',
'where' => ['locale' => '[a-zA-Z]{2}'],
'middleware' => 'setlocale'
],function () {
Route::get('/', [MainController::class, 'index'])->name('main.index');
Auth::routes();
Route::get('/home', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::group(['middleware' => ['auth']], function () {
//
});
});
I have added below code in Middleware,
public function handle(Request $request, Closure $next)
{
if (session()->has('locale')) {
App::setLocale(session()->get('locale'));
}
return $next($request);
}
In view file I have added this code,
<select class="form-control languageSelector">
<option {{ session()->get('locale') == 'en' ? 'selected' : '' }} value="en">πΊπΈ <span style="font-weight: bolder !important">En</span></option>
<option {{ session()->get('locale') == 'fr' ? 'selected' : '' }} value="fr">π«π· <span style="font-weight: bolder !important">Fr</span></option>
</select>
$(document).ready(function(){
var url = '{{ route('changeLang') }}';
$('.languageSelector').change(function(){
window.location.href = url + "?lang="+ $(this).val();
});
});
when I select language french from dropdown in route always see EN.
In Controller I have added,
public function changeLanguage(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
return redirect()->back();
}
How can I solve it?
Upvotes: 1
Views: 2720
Reputation: 65
Thanks Stack overflow. I have solve it by using this technique,
public function changeLanguage(Request $request)
{
App::setLocale($request->lang);
session()->put('locale', $request->lang);
$url = url()->previous();
$route = app('router')
->getRoutes($url)
->match(app('request')->create($url))
->getName();
return redirect()->route($route, ['locale' => $request->lang]);
}
Upvotes: 3
Reputation: 1
The better way to use the session for this purpose because its a cheap way to define URL with language code, and here is the best way you can use on anywhere. you can follow all instruction web.php kernal.php middleware at the end you wrote this line of code in controller? [1]: https://i.sstatic.net/p63eB.png
Upvotes: 0