Using the middleware option I gave in the second link you can change the language by a ?language=en parameter on any URL.
You can remove the code from the AppServiceProvider as the middleware will now be doing this part.
namespace App\Http\Middleware;
use Closure;
class Translate
{
protected $default = 'en';
protected $languages = [
'en',
'nl',
'fr',
];
public function handle($request, Closure $next)
{
if($request->has('language')) {
$lang = $request->language;
if(array_search($lang, $this->languages) === false) {
$lang = $this->default;
}
$request->session()->put('lang', $lang);
}
\LaravelLocalization::setLocale( $request->session()->get('lang') );
return $next($request);
}
}
Add it to your web middlewares:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, // <-- without this one, it wont work
// \Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\App\Http\Middleware\Translate::class, // <-- Add it here
],
'api' => [
'throttle:60,1',
'bindings',
],
];
And change your dropdown to this:
// changed the form to GET instead of POST, no need for a csrf this way either
<form method="get">
<select name="language" class="form-control font-weight-normal text-gray" id="language" onchange="localize">
<option value="en">English</option>
<option value="fr">French</option>
<option value="es">Spanish</option>
<option>5</option>
</select>
</form>
And remember not to use the route group of the package (the middleware is handling the language selection now)
// do not use this part of the LaravelLocalization package
Route::group(['prefix' => LaravelLocalization::setLocale()], function() {