有条件地运行中间件 - 拉拉维尔



我有一个中间件,它检查请求中的特定标头参数并基于该参数发回响应。

但我遇到的问题是我不希望这个中间件总是在我的控制器中的函数上运行。我希望中间件在函数中的条件为真时运行(例如:存储函数(。

我怎样才能做到这一点?

中间件在命中控制器操作之前被调用。因此,不可能根据操作中的条件执行中间件。但是,可以有条件地执行中间件:

通过请求

您可以将条件添加到请求对象(隐藏字段或类似字段(

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);
}

过孔参数

要将参数传递给中间件,必须在路由定义中设置该参数。定义路由,并将带有条件值的:(在本例中为布尔值(附加到中间件的名称。

路线/网络.php

Route::post('route', function () {
//
})->middleware('FooMiddleware:true');

中间件

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);
}

最新更新