如何在流明框架中获取中间件的当前路由?

I have develop the API application using lumen. And for the access permission control. I want to get the current route in middleware. But, I always get null on:

   $route = $request->route();

I already try the way on the Can I get current route information in middleware with Lumen? which using the routeMiddleware and dispatcher. But it's still return null. How could I get the current route on middleware?

Thank a lot..

Route::currentRouteName();

will return you the name of the route;

From the Laravel docs:

http://laravel.com/docs/5.1/requests#basic-request-information

The path method returns the request's URI. So, if the incoming request is targeted at http://domain.com/foo/bar, the path method will return foo/bar:

$uri = $request->path();

There are even other methods you may find helpful:

if ($request->is('admin/*')) {
    // do something
}

Unfortunately it's not possible. At least it's not as simple as calling getCurrentRoute().

You need to go through routes collection and match them again with request path.

Take a look at this rough example: https://gist.github.com/radmen/92200c62b633320b98a8

Please note that some parts of this code may not work ;) I've extracted this code from my app (slightly different use case) and tried to fit it to your case.

maybe this

$request   = new \Illuminate\Http\Request;
$method    = $request->getMethod();
$pathInfo  = app()->getPathInfo();
$routeName = app()->getRoutes()[$method.$pathInfo]['action']['as'];

There is a more elegant way of doing this.

Extend the Application class if you have not already and add this extra method:

use Laravel\Lumen\Application;

class YourApplication extends Application
{
    /** override other methods if needed */

    /**
     * @return string
     */
    public function getCurrentRoute()
    {
        return $this->currentRoute;
    }

}

Then you can access it in your Middleware like this:

$route = app()->getCurrentRoute();
$action = $route[1];
$info = $action['uses']; // string(57) "YourApp\Http\Controller\Public\UserController@view"

Please update your Lumen... Everything works with no issues

namespace App\Http\Middleware;

public function handle($request, Closure $next)
{
    $route = $request->route();
    $path = $request->getPathInfo();

    // your code here
    return $next($request);
}

in global middleware, you can not get route from request directly, but you can get if in a routeMiddleware.

so, just use routeMiddleware, and in middleware, $request->route().

if you just want to get it in a global middleware, just clone the $request, and set a dispatcher