I am trying to use the current route in middleware in Laravel 5.7 using the following line of code:
$route = Route::current();
But I get a null value for $route
. Any ideas?
I am trying to use the current route in middleware in Laravel 5.7 using the following line of code:
$route = Route::current();
But I get a null value for $route
. Any ideas?
The route couldn't be available yet because the router hasn't been yet called. That's depends on what middlewares are called before your middleware.
I think that, in a before middleware, you can try with: $route = $request->path();
just to be sure and not depending on the Router being booted or not.
You just want to change where your middleware is registered in app/Http/Kernel.php
if you need access to the Route facade.
I'm betting that your middleware is in the protected $middleware
array. It should be in one of your $middlewareGroups
usually web
or api
. Or if you need it for a specific route you can add it to the $routeMiddleware
array.
For example, I wanted to access Route
from within my HandleInertiaRequests
middleware so I had to move to $middlewareGroups
like shown in this screenshot: