I'm having a problem to build a translation switcher, this is what I have already did:
Step 1 : I have prefixed all the routes with the locale parameter {languge}
Route::redirect('/', '/en');
Route::group(['prefix' => '{language}'], function () {
//products routes
Route::get('/', 'ProductController@index' )->name('acceuil');
Route::get('/boutique/{slug}', 'ProductController@show' )->name('product.show');
Route::get('/search', 'ProductController@search' )->name('product.search');
});
step 2: then I created a middleware for setting the language of app depending on the request
public function handle($request, Closure $next)
{
App::setLocale($request->language);
return $next($request);
}
step 3: here I added Locale parameter {languge} to All Existing Links, like this:
<form method="POST" action="{{ route('register', app()->getLocale()) }}">
right here everything is fine but:
here I want to create a language switcher, this is what I did:
step 4: here I added Locale parameter {languge}to All Existing Links, like this:
<ul class="nav navbar-nav navbar-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{{ _('language') }}<span class="caret"></span></a>
<ul class="dropdown-menu">
<li><a href="{{ route( Route::currentRouteName(), 'fr' ) }}">{{ _('Francais') }}</a></li>
<li role="separator" class="divider"></li>
<li><a href="{{ route( Route::currentRouteName(), 'en' ) }}">{{ _('anglais') }}</a></li>
</ul>
</li>
</ul>
The problem is that I have different routes, some of them require a parameters and then Step 4 doesn't work:
ANY ideas ?
This seems to work for me:
{{ route(Route::currentRouteName(), array_merge(['fr'], array_slice(($rp = Route::current()->parameters()), 1, count($rp)))) }}
First we need to array_slice
the old language from the parameters then we can merge them with the new language. Since we merge the language with the current parameters, the order will always give us the language first and subsequent ordering of the current parameters.