Global middleware route parameter return null
Create a middleware and register it in the Kernel.php $middleware = []
Route
Route::get('/{parameter_name}', function () {
return view('welcome');
})->name('welcome');
Middleware
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
dump( $request->route('parameter_name') );
return $next($request);
}
@wkdcode-istvan Because all global middlewares are called before the request is dispatched to the router, you get the route as a null value. What do you really want to do?
That's the expected behavior and not a bug. All global middleware are executed before the request gets dispatched to the router (where the route parameter binding happens). You can use $request->route() only in a route level middleware.
EDIT: @xuanquynh was a few seconds faster 馃槃
@X-Coder264 It's so funny. Because you explain more details, it takes you more time than me. :)
Thanks guys,
I use modules with their own route files and I wanted to check the slug for the language code without adding a middleware to every route defined in the modules.
It make sense now, why didn't worked.
Thanks
@wkdcode-istvan in one of my middleware i did something like this:
if ($request->is('') ) {
// do something
}
and this seems to work!
as an aside you can do something like:
Route::middleware(['..'])->group(function () {
... routes
});
You can access the route if you apply the middleware at the group level (eg the web middleware group)
just not global.
Hi @shez1983,
Hi @rs-sliske,
Finally I have added the middleware to the web group and it works as it's should, just not global, but it's not a big issue. I can reuse the middleware in another modules as well if I need.
Thank you for your advice.
In case someone comes here as I did then you can use the middleware as after middleware to get those values.
public function handle ($request, Closure $next) {
$response = $next($request); // as it's after middleware, then all the routes are being parsed here everything went through.
// $request->route() will be non null this time
return $response;
}
Most helpful comment
That's the expected behavior and not a bug. All global middleware are executed before the request gets dispatched to the router (where the route parameter binding happens). You can use
$request->route()only in a route level middleware.EDIT: @xuanquynh was a few seconds faster 馃槃