有条件地运行中间件-Laravel [英] Run a middleware on condition - Laravel
问题描述
我有一个中间件,可以检查请求中的特定标头参数,并根据该参数发送回响应.
I have a middleware that checks for a specific header parameter in the request and sends back a response based on that.
但是我遇到的问题是我不希望这个中间件总是在Controller的某个函数上运行.我希望如果条件在函数(例如:存储函数)中成立,则中间件将运行.
But the problem I have is that I don't want this middleware run always on a function in my Controller. I want that middleware runs if a condition gets true in a function (for example: store function).
我该如何实现?
推荐答案
在触发控制器操作之前,将调用中间件.因此,不可能基于动作内部的条件来执行中间件.但是,可以有条件地执行中间件:
Middlewares are called before hitting an controller action. So its not possible to execute a middleware based on a condition inside an action. However, it is possible to conditional execution of middleware:
您可以将条件添加到请求对象(隐藏字段或类似字段)
You can add the condition to the request object (hidden field or similar)
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);
}
通过参数
要将参数传递给中间件,必须在路由定义中进行设置.定义路由,并在中间件名称后添加:
和条件值(在此示例中为boolean).
Via parameter
To pass a parameter to the middleware, you have to set it in the route definition. Define the route and append a :
with the value of the condition (in this example a boolean) to the name of the middleware.
routes/web.php
routes/web.php
Route::post('route', function () {
//
})->middleware('FooMiddleware:true');
FooMiddleware
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);
}
这篇关于有条件地运行中间件-Laravel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!