php - 如何在没有要验证的特定属性的情况下验证发布请求

标签 php laravel laravel-validation laravel-request

我有一个时间跟踪应用程序,每次要添加新的时间条目时,我必须首先验证所有先前的时间条目是否已关闭(意味着已设置结束日期)并抛出错误使用 validate() 方法发送消息。

我不知道这有多可行或如何做到这一点,阅读文档似乎大多数客户规则都要求给出一个属性,但在这种情况下,更多的是验证逻辑要求而不是形式发布请求。

当我收到发布请求时,我会获取发布请求开始时间之前且尚未给出结束时间的所有先前时间条目。

理想情况下,如果我返回任何时间条目,我会抛出一个错误,指出“您需要在打开新时间条目之前关闭上一个时间条目”。

为了更清楚起见,以下是我想要在代码中执行的操作:

$timeEntry= new TimeEntry;
$openTimeEntries = $timeEntry->Where('start_time', '<', $request->startTime)->Where('end_time', 0)->get();
$count = $openTimeEntries->count();

$request->validate([
    'comment' => 'string',
    'candidateId' => 'required',
    'startTime' => 'required|date',
    'endTime' => 'date|nullable|after:startTime',
    'CustomeTimeEntryRule' => $openTimeEntries->count() > 0, // If false I want this rule to add the message to the validate error array
]);

最佳答案

你走在正确的道路上。

但是,如果您确实自定义验证,则应该创建 here 的请求您可以阅读更多相关内容。

只需调用php artisan make:request TimeEntryStoreRequest

public function rules()
{
    return [
       'CustomeTimeEntryRule' => $openTimeEntries->count() > 0,
    ];
}

/**
 * @return array|string[]
 */
public function messages(): array
{
    return [
        'CustomeTimeEntryRule.*' => 'Custom message',
    ];
}

但是,如果它不是用户输入的表单,我认为您应该在 Controller 内而不是表单中检查它。

您还可以像这样简化代码:

use App\Models\TimeEntry;

$openTimeEntriesCount = TimeEntry::select('id')->where('start_time', '<', $request->startTime)->where('end_time', 0)->count();

关于php - 如何在没有要验证的特定属性的情况下验证发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71417513/

相关文章:

php - 在产品页面上显示可用库存数量

php - Laravel 验证器无法正常工作 - 重定向主页

Laravel 有时验证规则不起作用

laravel - 通过Mac OS X连接到存在于Docker中的远程数据库

php - Laravel JWT 多页面结构

php - 修改 Laravel 验证消息响应

php - 从两个不同的表计算价格+使用php和mysql

php - 如何使用 Aptana 调试 PHP Web 应用程序

php - 使用过去 2 个月(日期)

Laravel 5.8 - 未找到类 'Arr'