4

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?

Udhav Sarvaiya
  • 9,380
  • 13
  • 53
  • 64
Farzan Badakhshan
  • 373
  • 1
  • 5
  • 19

2 Answers2

4

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.

dparoli
  • 8,891
  • 1
  • 30
  • 38
1

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:

enter image description here

Dan Fletcher
  • 1,099
  • 11
  • 29