存在规则在空值上失败,即使与可为空的规则结合使用也是如此



我在当前的项目中使用Laravel 5.6。在请求对象的规则中,我有以下规则函数:

public function rules()
{
    if ($this->input('preset') === self::NO_PRESET) {
        $this->merge(['preset' => null]);
    }
    return [
        'preset' => 'nullable|exists:roles_presets,id',
        ...
    ];
}

但是,当"预设"为空时,exists:roles_presets,id规则仍然失败。难道不应该因为字段为 null 并且 nullable 规则允许这样的值而无法访问它吗?

不要将合并放在 rules 函数中,而是覆盖validationData并在那里添加逻辑。

public function validationData()
{
    if ($this->input('preset') === self::NO_PRESET) {
        $this->merge(['preset' => null]);
    }
    // returns $this->all();
    return parent::validationData();
}

最新更新