内容纲要

弄一个基类,然后在基类中验证是一种很古老的方式,在 Laravel 可通过中间件来鉴权

创建 app/Http/Middleware/AdminMiddleware.php

[code language=”php”]
<?php
namespace App\Http\Middleware;
use Closure;
class AdminMiddleware
{
/**
* Handle an incoming request. User must be logged in to do admin check
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if (\Auth::user()->user_type == ‘Admin’)
{
return $next($request);
}
return redirect()->guest(‘/’);
}
}
[/code]

在 app/Http/Kernel.php 中注册中间件

[code language=”php”]
protected $routeMiddleware = [
‘auth’ => \Illuminate\Auth\Middleware\Authenticate::class,
‘auth.basic’ => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
‘bindings’ => \Illuminate\Routing\Middleware\SubstituteBindings::class,
‘can’ => \Illuminate\Auth\Middleware\Authorize::class,
‘guest’ => \App\Http\Middleware\RedirectIfAuthenticated::class,
‘throttle’ => \Illuminate\Routing\Middleware\ThrottleRequests::class,
‘admin’ => \App\Http\Middleware\AdminMiddleware::class,
];
[/code]

然后修改路由 routes/web.php

[code language=”php”]
Route::group(array(‘prefix’=>’administration’,’middleware’ => [‘auth’, ‘admin’]), function ()
{
Route::get(‘dashboard’,function(){
return "Welcome to Administration";
});
});
[/code]

发表评论

电子邮件地址不会被公开。 必填项已用*标注