创建中间件
php artisan make:middleware [middleware name]
编写中间件代码
<?php
namespace App\Http\Middleware;
use Closure;
class Test
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
//在请求之前 做一些操作
......
$response = $next($request);
//next 下面在响应之后 做一些操作
......
return $response;
}
}
将上述中间件注册到 app/Http/kernel.php 的 $routeMiddleware 属性中:
protected $routeMiddleware = [
... // 其他中间件
'test' => \App\Http\Middleware\Test::class,
];;
使用中间件 在 /routes/web.php 或 api.php
Route::group(['middleware' => ['test'],'prefix'=>'admin','namespace'=>'Admin'],function (){
//你的路由
});
done