php - 在条件下运行中间件 - Laravel
问题描述
我有一个中间件,用于检查请求中的特定标头参数并基于该参数发回响应。
但我遇到的问题是我不希望这个中间件总是在我的控制器中的一个函数上运行。如果函数中的条件为真(例如:存储函数),我希望中间件运行。
我怎样才能做到这一点?
解决方案
在执行控制器操作之前调用中间件。因此,不可能根据动作中的条件执行中间件。但是,可以有条件地执行中间件:
通过请求
您可以将条件添加到请求对象(隐藏字段或类似字段)
public function handle($request, Closure $next)
{
// Check if the condition is present and set to true
if ($request->has('condition') && $request->condition == true)) {
//
}
// if not, call the next middleware
return $next($request);
}
通过参数
要将参数传递给中间件,您必须在路由定义中进行设置。定义路由并将:
带有条件值(在本例中为布尔值)的 a 附加到中间件的名称中。
路线/web.php
Route::post('route', function () {
//
})->middleware('FooMiddleware:true');
Foo中间件
public function handle($request, Closure $next, $condition)
{
// Check if the condition is present and set to true
if ($condition == true)) {
//
}
// if not, call the next middleware
return $next($request);
}
推荐阅读
- python - Firestore 事务仅以静默方式失败
- linux - 使用 bash 脚本从字符串中删除一组特殊字符
- pandas - 自定义过滤和排序
- c# - C# ImageProcessor.ImageFactory 不会减少 PNG 图像文件的大小,适用于 JPG
- html - FullCalendar:初始大小错误
- javascript - WebRTC 没有获得流的两个桌面显示器的分辨率
- javascript - Firebase 在 onAuthStateChange 之后获取子级但出现错误客户端处于脱机状态
- node.js - 每当我导入我的装饰器时,我都会收到 MODULE_NOT_FOUND
- docker - docker -i -t 和 -it 标志之间的区别
- c# - 如何在 Json 模式响应中重命名类