I set up mcamara/laravel-localization 1.3 library in laravel 5.6
according to the documentation and in users
table i create lang
column which i set every time user switch language (this allow me to send "background" cyclic emails in proper language or set proper language after user login). I set all my routes in web.php
in group LaravelLocalization::setLocale()
(as documentation says).
I want to use named routes inside my controllers e.g. for redirection to proper page after user login (user came from EN landing page, but his lang='pl'
). When in my LoginController@redirectTo()
I use just:
App::setLocale(Auth::user()->lang);
$url = route('dashboard.index');
return $url;
// current result $url = 'http://ebnavi.localhost/en/panel/raporty'
// desired result $url = 'http://ebnavi.localhost/pl/panel/raporty'
It doesn't work. I don't found direct instruction in documentation about this.
So how to do it?
After few hours finally I found this solution in internet:
$url = LaravelLocalization::getLocalizedURL($locale, route($routeName));
And create following helper function to realize this task
function localRoute($routeName, $locale = null)
{
if (!$locale && Auth::user()) $locale = Auth::user()->lang;
return $locale ? LaravelLocalization::getLocalizedURL($locale, route($routeName)) : route($routeName);
}
In our controller we can just use it in this way:
$url = localRoute('dashboard.index');
But may be exists some better approach for this?