代码之家  ›  专栏  ›  技术社区  ›  Jacobo

Laravel在更新时忽略唯一验证

  •  0
  • Jacobo  · 技术社区  · 6 年前

    我的验证规则如下:

    $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',
    ];
    

    我遇到的麻烦是 属性\u id . 这在当前表(即预订)中必须是唯一的。

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

    当我做一个 Log::info 在我所有的规则中,我有以下几行: 'property_id' => 'required|exists:properties,id|unique:reservations,property_id,4',

    但我一直收到错误。我做错什么了吗?

    2 回复  |  直到 6 年前
        1
  •  1
  •   Jacobo    6 年前

    错误在这一行:

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

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

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

        2
  •  -1
  •   Bonish Koirala    6 年前

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

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