【问题标题】:Unique rule, ignore null value唯一规则,忽略空值
【发布时间】:2019-09-21 09:07:08
【问题描述】:

我有一个FormRequest,我想在更新行时验证字段fiscal_id 的唯一性,验证工作,但问题是fiscal_id 可能为空,所以如果更新它我发送null,唯一规则不通过。

'fiscal_id' => [
    'sometimes', 
    Rule::unique('table', 'fiscal_id')->where(function($query) {
        $query->whereNull('deleted_at')
            ->where('company_id', auth()->user()->company_id);
    })->ignore($this->route('customer')->id)
]

null 时,我如何验证fiscal_id 的唯一性(因为有其他字段带有null 所以它失败了)。

【问题讨论】:

  • 试试nullable验证?
  • 是的,你应该使用 nullable 而不是有时。

标签: laravel validation


【解决方案1】:

尝试像这样分开验证创建和更新

public function rules() {
    // rules for updating record
    if ($this->method() == 'PATCH') {
        return [
            'fiscal_id' => [
                 'nullable',
                 Rule::unique('table', 'fiscal_id')->where(function($query) {
                    $query->whereNull('deleted_at')
                 ->where('company_id',auth()->user()->company_id);
                 })->ignore($this->route('customer')->id)
             ]
        ];
    } else {
    // rules for creating record
        return [
            'fiscal_id' => [
                 'required',
                 Rule::unique('table', 'fiscal_id')->where(function($query) {
                    $query->whereNull('deleted_at')
                 ->where('company_id',auth()->user()->company_id);
                 })
             ]
        ];
    }

}

【讨论】:

    猜你喜欢
    • 2020-09-13
    • 1970-01-01
    • 2016-12-22
    • 2019-07-20
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 2016-02-03
    相关资源
    最近更新 更多