一,官方的文档:
参考地址:
https://docs.golaravel.com/docs/middleware
二,演示:
功能:一个中间件负责验证用户是否已登录,
传递参数的作用是:在已登录基础是否验证真人身份核验,值为1时要核验,其他情况可以不用
1, 为中间件注册一个别名:
bootstrap/app.php
->withMiddleware(function (Middleware $middleware) {//为中间件注册别名$middleware->alias(['check' => Check::class]);//应用中间件$middleware->append(Sign::class);})
2,在routes/api.php中传递参数:
//评论功能
Route::controller(CommentController::class)->group(function () {Route::post('/comment/list', 'list')->middleware('check:1');Route::post('/comment/detail', 'detail')->middleware([Check::class]);
});
3,在中间件中接收参数
class Check
{/*** Handle an incoming request.** @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next*/public function handle(Request $request, Closure $next, $isNeedAuth='0'): Response{//如果$isNeedAuth值为1,则需要验证用户是否已真人核验if ($isNeedAuth == 1) {echo "isNeedAuth:值为1<br/>";} else {echo "isNeedAuth:值为0<br/>";}}
}