Laravel中间件无法正常工作

时间:2018-01-28 07:34:00

标签: php laravel routes laravel-5.3 middleware

我有一个中间件类: -

<?php

namespace App\Http\Middleware;


use Closure;

class isAdmin
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if(auth()->user()->getIsAdminAttribute()){

            return $next($request);


        }
        abort(404);
    }
}

在Kernel.php文件中: -

<?php

namespace App\Http;

use App\Http\Middleware\isAdmin;

protected $routeMiddleware = [
        'isAdmin' => isAdmin::class,
    ];

在web.php路由文件中: -

Route::get('users/list', 'UsersController@listUsers')->name('List_Users')->middleware('isAdmin');

我试图转储

dd(auth()->user()->getIsAdminAttribute());

没有任何事情发生,就像我根本没有将isAdmin中间件分配给该路径一样。

2 个答案:

答案 0 :(得分:-1)

您可以使用以下命令检查分配给他们的路线和中间件:

php artisan route:list

应该是这样的:

+--------+----------+-------------+------------+-------------------------------------------------+--------------+
| Domain | Method   | URI         | Name       | Action                                          | Middleware   |
+--------+----------+-------------+------------+-------------------------------------------------+--------------+
|        | GET|HEAD | /           |            | Closure                                         | web          |
|        | GET|HEAD | users/list  | List_Users | App\Http\Controllers\UsersController@listUsers  | web,isAdmin  |
+--------+----------+-------------+------------+-------------------------------------------------+--------------+

请注意中间件列中的isAdmin。

答案 1 :(得分:-1)

我知道您来晚了,但也许其他人会从中受益, 我遇到了同样的问题,经过一些调试后,我发现该中间件未触发,并且由于Route :: get('post / {id}')而出现在route:list中,即使我将此路由放在遇到问题Route :: get('post / create')的路线,我将显示路线从post更改为post,然后再次触发了中间件。