我试图在Laravel 5.3中创建一个中间件,检查用户是否是管理员,这样我就可以将某些路由限制为仅限管理员。
我的中间件:
<?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()->hasRole('admin') ) {
return redirect('login');
}
return $next($request);
}
}
我在Kernal中注册它,将ti添加到受保护的内容中,如下所示:
protected $routeMiddleware = [
....
'isadmin' => App\Http\Middleware\IsAdmin::class,
]
然后我尝试用以下方法保护我的路线:
Route::resource('user', 'UserController')->middleware('isadmin');
但我从路径文件中得到错误:
FatalThrowableError in web.php line 103:
Call to a member function middleware() on null
答案 0 :(得分:3)
您应该使用::group()
:
Route::group(['middleware' => 'isadmin'], function () {
Route::resource('user', 'UserController');
});
答案 1 :(得分:0)