How to get Route in Middleware in Laravel

2020-06-03 04:11发布

问题:

Currently I can get a route in a controller by injecting it into the method I want to use it in.

<?php namespace App\Http\Controllers;

use Illuminate\Routing\Route;

class HomeController extends Controller
{
    public function getIndex(Route $route)
    {
        echo $route->getActionName();
    }
}

However I'm trying to perform something similar in middleware but can't get it going.

<?php namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Route;
use Illuminate\Contracts\Routing\Middleware;

class SetView implements Middleware {

    protected $route;

    public function __construct(Route $route)
    {
        $this->route = $route;
    }

    public function handle($request, Closure $next)
    {
        echo $this->route->getActionName();

        return $next($request);
    }
}

Getting an error.

Unresolvable dependency resolving [Parameter #0 [ <required> $methods ]] in class Illuminate\Routing\Route

Not really sure what to do with that. Don't really care if it's a route or not, but need to get that action name somehow.

回答1:

Remove your constructor/put it to default like;

public function __construct(){}

Try accessing the route via the handle method like so;

 $request->route();

So you should be able to access the action name like so;

 $request->route()->getActionName();

If the route return is null be sure you have registered the middleware within the App/Http/Kernel.php, like so;

protected $middleware = [
    ...
    'Path\To\Middleware',
];

The above is for global middleware

For route specific filtering place the 'Path\To\Middleware', within the middleware array within RouteServiceProvider.php within the App\Providers folder.

You can also access the route object via app()->router->getCurrentRoute().

Edit:

You could possibly try the following;

$route = Route::getRoutes()->match($request);
$route->getActionName();

This get the route from the RouteCollection. Be sure to encapsulate this within a try catch as this will throw a NotFoundHttpException.



回答2:

For Laravel 5.1.x

In your global middleware

use Illuminate\Support\Facades\Route;

$route = Route::getRoutes()->match($request);
$currentroute = $route->getName();