一、创建 middleware
php artisan make:middleware MustBeAnAdmin
修改生成的文件:app/Http/Middleware/MustBeAnAdmin.php
public function handle($request, Closure $next)
{
if($request->user() && $request->user()->isAdmin()){
return $next($request);
}
return redirect('/');
}
app/User.php 新增 isAdmin() 方法
public function isAdmin()
{
return $this->hasRole('admin');
}
二、注册 middleware
app/Http/Kernel.php 注册 middleware
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'admin' => \App\Http\Middleware\MustBeAnAdmin::class,
];
app/Http/Controllers/PostsController.php 注册 middleware
public function __construct()
{
\Auth::loginUsingId(1);
$this->middleware('admin');
}
三、测试
修改 app/Http/Controllers/PostsController.php
public function show($id)
{
$post = Post::findOrFail($id);
return $post->title;
}
访问:http://localhost:8000/posts/1,正常返回
修改 app/Http/Controllers/PostsController.php,登录 id=2 的用户
public function __construct()
{
\Auth::loginUsingId(2);
$this->middleware('admin');
}
访问:http://localhost:8000/posts/1,发现重定向到首页