什么是中间件
Laravel中间件是触发路由事件之前或之后执行的一段代码。中间件常用于用户身份识别,CSRF保护。用户触发路由事件的时候,经常
需要判断一下用户的身份,这时候就可以使用中间件了。Laravel中间件存放于app/Http/Middleware
。
新建一个中间件
在Laravel项目根目录执行php artisan make:middleware AuthAdminMiddleware
就在app/Http/Middleware
位置生成了AuthAdminMiddleware.php
文件,然后添加逻辑代码AuthAdminMiddleware.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
namespace App\Http\Middleware;
use Closure;
class AuthAdminMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if( $request->user()['role'] != 'admin' ) return redirect('/');
return $next($request);
}
}
这是一个用于后台的中间件,若用户身份不为管理员,则重定向到首页
注册中间件
新建中间件后必须注册才能使用。编辑app/Http/Kernel.php
,在$routeMiddleware
数组里面添加一行'admin' => AuthAdmin::class
使用PhpStorm会自动补全命名空间Kernel.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
namespace App\Http;
use App\Http\Middleware\AuthAdmin;
use Illuminate\Foundation\Http\Kernel as HttpKernel;
class Kernel extends HttpKernel
{
/**
* The application's global HTTP middleware stack.
*
* These middleware are run during every request to your application.
*
* @var array
*/
protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
];
/**
* The application's route middleware groups.
*
* @var array
*/
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\App\Http\Middleware\VerifyCsrfToken::class,
],
'api' => [
'throttle:60,1',
],
];
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'admin' => AuthAdmin::class
];
}
使用中间件
编辑app/Http/routes.php
,添加1
2
3
4
5
6Route::group([
'prefix' => 'admin',
'middleware' => ['web', 'auth', 'admin']
], function () {
require (__DIR__ . '/Routes/AdminRoute.php');
});
prefix
是路由前缀,middleware
为这个路由分组里面使用的中间件
当路由较多时,可以使用require
导入路由文件
app/Http/Routes/AdminRoute.php
1
2
3
4
5
Route::get('/', [
'as' => 'admin.index',
'uses' => 'AdminController@index'
]);