我有一个中间件,可以检查请求中的特定标头参数,并根据该参数发送回响应。
但是我的问题是我不希望这个中间件总是在Controller的某个函数上运行。我希望如果条件在函数中成立(例如:store function),则中间件将运行。
我该如何实现?
参考方案
在执行控制器操作之前,将调用中间件。因此,不可能基于动作内部的条件执行中间件。但是,可以有条件地执行中间件:
通过请求
您可以将条件添加到请求对象(隐藏字段或类似字段)
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)。
路线/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);
}
Laravel Blade模板尝试获取非对象的属性时如何返回null而不是ErrorException - php我正在编写一些Laravel Blade模板,并且我的模型可能包含空对象。我非常想尝试获取对象属性,如果有错误,则返回null。因此,不必编写以下代码:@if ($model->child_object_that_may_be_null) {{ $model->child_object_that_may_be_null->interesti…
Laravel-无需登录即可认证用户 - php在laravel 5.4中,可以在不登录用户的情况下对用户进行身份验证吗?从laravel doc中,我能找到的最接近的东西是:Auth::once($credentials) 但这仍然使该用户感到厌烦。我需要做的就是只是知道使用该电子邮件和密码的用户是否存在。 参考方案 您可以将Auth::attempt函数与第三个参数用作false进行登录 $email…
Laravel WHERE查询单列结果 - php我有以下控制器,应该返回所有尚未验证的用户。public function getUserRequests() { $userRequests = User::where('status' ,"Not Verified"); foreach($userRequests as $user) { echo $user-&g…
Laravel 5错误报告抑制 - php在Laravel 4中,抑制E_NOTICE消息很容易;我似乎无法做到这一点,因为如果我添加error_reporting(E_ALL ^ E_NOTICE) 它只是被覆盖的任何地方。这似乎发生在这里:(index.php)$response = $kernel->handle( $request = Illuminate\Http\Request::…
Laravel 5排序具有关系的雄辩模型 - php我有一个要基于关系属性进行排序的模型。主模型Resultado具有类型respondente的关系belongsTo,而respondente具有关系usuario。我想获取具有这些关系的Resultado并按usuario name属性(列)对结果进行排序。我试过了$resultados = Diagnostico\Resultado::with(…