I have a multi lingual website. where i want to add current locale as prefix for all of my project routes. For that to be than any time i use a route i must always provide a value for locale parameter of the route. I think there are better ways of doing this.
My routes looks like this
Route::prefix('{locale}')->group(function() {
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/blog', [App\Http\Controllers\PostController::class, 'index'])->name('blog');
});
I want my path in url looks like this.
- http://localhost/project/en/blog or
- http://localhost/project/fa/blog
I also have a middleware SetLocale
where I decide app locale according to the request path coming through;
here is my middleware code
class SetLocale
{
public function handle(Request $request, Closure $next)
{
$locale = $request->segment(1);
if (! is_null($locale) && ! in_array($locale, config('app.locales')) ) // config('app.locales') = ['en', 'ar', 'fa']
abort(404);
$html_dir = in_array($locale, ['en'])?'ltr':'rtl';
\Illuminate\Support\Facades\Config::set('app.html_dir', $html_dir);
\Illuminate\Support\Facades\App::setLocale($locale);
return $next($request);
}
}
CodePudding user response:
You can use the defaults
method of the URL Generator do this exact thing:
URL::defaults(['locale' => $locale]);
Add that in your middleware and the locale
parameter will have a default when generating a URL to routes using that parameter.
Laravel 8.x Docs - URL Generation - Default Values defaults
CodePudding user response:
You have to do it via Group Routes
https://laravel.com/docs/8.x/routing#route-groups.
Okay sorry. then what about following?
Route::prefix('{locale}')->middleware('SetLocale')->group(function() {
Route::get('/', [App\Http\Controllers\HomeController::class, 'index'])->name('home');
Route::get('/blog', [App\Http\Controllers\PostController::class, 'index'])->name('blog');
});