I am adding localization in my Laravel app.
Let’s say I have the routes slots
and slots/{id}
. My problem is, when I try to go to slots/{id}
page, the controller that handles this route expects $locale
as the first variable of the function.
This is my function:
public function show($locale, Slot $slot)
{
dump($locale);
return view('slots.show', [
'slot' => $slot,
]);
}
What I’d like is avoid having to pass the $locale
variable to every functions of my controllers. Is there a way to do that? Like this:
public function show(Slot $slot)
{
return view('slots.show', [
'slot' => $slot,
]);
}
I am trying to achieve this without having to add any package like laravel-localization
.
This is my middleware:
<?php
namespace AppHttpMiddleware;
use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesURL;
use SymfonyComponentHttpFoundationResponse;
class SetLocale
{
/**
* Handle an incoming request.
*
* @param Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse) $next
*/
public function handle(Request $request, Closure $next): Response
{
app()->setLocale($request->segment(1));
URL::defaults(['locale' => $request->segment(1)]);
return $next($request);
}
}
This is what my web.php looks like:
Route::prefix('{locale}')
->where(['locale' => '[a-zA-Z]{2}'])
->middleware('setlocale')
->group(function () {
Route::domain('{portal:slug}.' . env('APP_DOMAIN'))->name('portal.')->group(function () {
Route::get('/', function () {
return redirect()->route('dashboard');
});
Route::middleware(['auth', 'verified', 'institution', 'goodDb'])->group(function () {
Route::resource('slots', SlotController::class);
});
Route::get('/', function () {
return redirect(app()->getLocale());
});
Any help would be greatly appreciated! Thanks!