Get current route action name from middleware in l

2019-06-26 00:11发布

I have a middleware like this:

<?php
namespace App\Http\Middleware;

use App\Contracts\PermissionsHandlerInterface;
use Closure;

class PermissionsHanlderMiddleware {

    public $permissionsHandler;

    function __construct(PermissionsHandlerInterface $permissionsHandler) {
        $this -> permissionsHandler = $permissionsHandler;
    }

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next) {
        $routeAction = $request->route()->getActionName();

        /*
         do some operations
        */

        return $next($request);
    }

}

but $request->route() always returns null, I think its because the router hasn't been dispatched with the request.

Note: I added my middleware to Kernal.php global middlewares to run before each request as the following

protected $middleware = [
        .
        .
        .
        'App\Http\Middleware\PermissionsHanlderMiddleware',
    ];

I want to get route action name before the execution of $next($request) to do some permission operations. How can i do this ?

2条回答
成全新的幸福
2楼-- · 2019-06-26 00:34

You cannot get the route action name if the router has not yet been dispatched. The router class has not yet done its stuff - so you cannot do $router->request() - it will just be null.

If it runs as routeMiddleware as $routeMiddleware - then you can just do $router->request()

You can get the URI string in the middleware before the router has run - and do some logic there if you like: $request->segments(). i.e. that way you can see if the URI segment matches a specific route and run some code.

Edit:

One way I can quickly think of is just wrap all your routes in a group like this:

$router->group(['middleware' => 'permissionsHandler'], function() use ($router) {
            // Have every single route here
});
查看更多
爷的心禁止访问
3楼-- · 2019-06-26 00:40

This is the solution I did in my project:

...
public function handle($request, Closure $next) {
    DB::beginTransaction();
    $nextRequest = $next($request); //The router will be dispatched here, but it will reach to controller's method sometimes, so that we have to use DB transaction.
    $routeName = $request->route()->getRouteName();
    if ($checkPassed) {
        DB::commit();
        return $nextRequest;
    } else {
        DB::rollback();
    }
}
查看更多
登录 后发表回答