运行 条件中间件 - Laravel
Run a middleware on condition - Laravel
我有一个中间件可以检查请求中的特定 header 参数并根据该参数发回响应。
但我遇到的问题是我不希望这个中间件 运行 总是在我的控制器中的一个函数上。如果条件在函数中为真(例如:存储函数),我想要那个中间件 运行s。
我怎样才能做到这一点?
在执行控制器操作之前调用中间件。因此不可能根据动作中的条件执行中间件。但是,可以有条件地执行中间件:
通过请求
您可以将条件添加到请求对象(隐藏字段或类似字段)
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);
}
通过参数
要将参数传递给中间件,您必须在路由定义中设置它。定义路由并将带有条件值(在本例中为布尔值)的 :
附加到中间件的名称。
routes/web.php
Route::post('route', function () {
//
})->middleware('FooMiddleware:true');
FooMiddleware
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);
}
我有一个中间件可以检查请求中的特定 header 参数并根据该参数发回响应。
但我遇到的问题是我不希望这个中间件 运行 总是在我的控制器中的一个函数上。如果条件在函数中为真(例如:存储函数),我想要那个中间件 运行s。
我怎样才能做到这一点?
在执行控制器操作之前调用中间件。因此不可能根据动作中的条件执行中间件。但是,可以有条件地执行中间件:
通过请求
您可以将条件添加到请求对象(隐藏字段或类似字段)
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);
}
通过参数
要将参数传递给中间件,您必须在路由定义中设置它。定义路由并将带有条件值(在本例中为布尔值)的 :
附加到中间件的名称。
routes/web.php
Route::post('route', function () {
//
})->middleware('FooMiddleware:true');
FooMiddleware
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);
}