【问题标题】:Laravel ignore unique validation on updateLaravel 忽略更新时的唯一验证
【发布时间】:2018-11-04 04:16:22
【问题描述】:

我有一个包含许多外键的模型。这些外键之一必须是唯一值。

我的验证规则如下:

$data['rules'] = [
    'address' => 'required|string',
    'buyer_id' => 'required|exists:buyers,id',
    'buyer_name' => 'required|string',
    'date' => 'required|date',
    'email' => 'required|email',
    'identification_photo' => 'required|string',
    'invoice' => 'string|required',
    'middleman_id' => 'nullable|exists:middlemen,id',
    'price' => 'required|numeric|between:1,99999999999999999999999999.9999',
    'property_id' => 'required|exists:properties,id|unique:reservations,property_id',
    'purchase_receipt' => 'required|string',
    'rfc' => array(
        'required',
        'regex:/^([A-Z,Ñ,&]{3,4}([0-9]{2})(0[1-9]|1[0-2])(0[1-9]|1[0-9]|2[0-9]|3[0-1])[A-Z|\d]{3})$/'
    ),
    'tier_id' => 'nullable|exists:tiers,id',
    'user_id' => 'required|exists:users,id',
];

我遇到的麻烦是 property_id。这在当前的预订表中必须是唯一的。

为了在我进行更新时忽略该验证,我在调用验证器之前添加了这行代码: $book['rules']['property_id'] .= ",{$item->property_id}";

当我对所有规则执行Log::info 时,我得到以下行:'property_id' => 'required|exists:properties,id|unique:reservations,property_id,4',

但我不断收到错误消息。我做错了吗?

【问题讨论】:

    标签: laravel laravel-5 eloquent


    【解决方案1】:

    错误在这一行:

    $book['rules']['property_id'] .= ",{$item->property_id}";
    

    您必须提供当前模型 ID 才能忽略对特定项目的验证,而不是传递要忽略的外键的 ID。

    $book['rules']['property_id'] .= ",{$item->id}";
    

    这样您就可以告诉您对于 id = x 的模型,忽略该特定验证。为了更好地理解它,您告诉我们,对于此验证,仅对 id 等于 $item->id 的记录忽略属性验证。

    【讨论】:

      【解决方案2】:

      我认为您正在寻找的代码行是

      'property_id' => 'required|exists:properties,id|unique:reservations,property_id,'.$request->id',

      这会忽略您正在更新的当前行,同时还会验证您的 property_id

      【讨论】:

        猜你喜欢
        • 2020-09-13
        • 2017-10-05
        • 1970-01-01
        • 2018-10-26
        • 2021-02-07
        • 2014-06-28
        • 2021-11-05
        • 2014-08-20
        • 1970-01-01
        相关资源
        最近更新 更多