Info: I'm using Larvel Version 6.1.0 and I want my website to support different languages. Therefore I created a new middleware and wanted to give my routes a prefix so Laravel can determine the languages.Maybe there's a better way but here's what I did so far.
The urls are supposed to look like this in the end:
mywebsite.com/en/home , url/locale/home
The middleware to set the locale
namespace App\Http\Middleware;
use Closure;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
app()->setLocale($request->segment(1));
return $next($request);
}
}
Registered the new middleware setlocale in kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'setlocale' => \App\Http\Middleware\SetLocale::class,
];
My web.php
Route::group(['middleware' => ['setlocale'],'prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}']], function() {
Route::get('/', 'NewController@frontpage');
Route::get('/home', 'NewController@frontpage')->name("home");
Auth::routes();
});
For some reason the prefix part in my route group isn't working at all. When I enter mywebsite.com/en/home in my browser I get
Missing required parameters for [Route: login] [URI: {locale}/login]
Which is strange because I didn't request the login route but the home route and I passed a locale. Does anyone see the error or has a better idea to implement support for several languages in Laravel Version 6 ?
Thanks in advance.