laravel 理解中间件用法

定义中间件

php artisan make:middleware CheckToken

<?php

namespace App\Http\Middleware;

use Closure;

class BeforeMiddleware
{
public function handle($request, Closure $next)
{
// 执行动作

return $next($request);
}
}

注册中间件

首先应该在 app/Http/Kernel.php 文件中分配给该中间件一个 key,默认情况下,该类的 $routeMiddleware 属性包含了 Laravel 自带的中间件,要添加你自己的中间件

中间件在 HTTP Kernel 中被定义后,可以使用 middleware 方法将其分配到路由:

Route::get('admin/profile', function () {
//
})->middleware(CheckToken::class);


带参数的中间件

<?php

namespace App\Http\Middleware;

use Closure;

class CheckRole
{
/**
* 处理输入请求
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string $role
* @return mixed
* translator https://xueyuanjun.com
*/
public function handle($request, Closure $next, $role)
{
if (! $request->user()->hasRole($role)) {
// Redirect...
}

return $next($request);
}

}

 

终端中间件

<?php

namespace Illuminate\Session\Middleware;

use Closure;

class StartSession
{
public function handle($request, Closure $next)
{
return $next($request);
}

public function terminate($request, $response)
{
// 存储session数据...
}
}

 
上一篇:OS Week1-L1: Intro


下一篇:【论文阅读】Relation classification via multi-level attention CNNs[ACL2016]