Laravel 验证:更新期间忽略某些字段

问题描述 投票:0回答:1

如何防止 Laravel 在编辑现有用户时验证某些列?我正在尝试更新客人的信息,但如果未对客人的详细信息进行任何更改,我想忽略电话和电子邮件字段。但是,在创建新来宾时,应正确检查唯一性。我怎样才能实现这个目标?我已经被这个问题困扰了一段时间了。

这是我的表单验证规则:

return [
    'first_name' => 'required|string|max:255',
    'last_name' => 'nullable|string|max:255',
    'other_names' => 'nullable|string|max:255',
    'city' => 'nullable|string|max:255',
    'country' => 'nullable|string|max:255',
    'email' => ['required_if:phone,null', Rule::unique('guests')->whereNot('email',null)->where('hotel_id',auth()->user()->hotel_id) ],
    'phone' => ['required_if:email,null', Rule::unique('guests')->where('phone','!=', $request->phone)->where('hotel_id',auth()->user()->hotel_id) ],
    'address' => 'nullable|string|max:255', 
    'other_phone' => 'nullable|numeric:11',    
];

如有任何帮助,我们将不胜感激。

php laravel forms validation request
1个回答
0
投票

您可以使用

Rule::unique()
方法在验证过程中忽略某个 ID。当更新模型并想要忽略模型本身时,这非常有用。

use Illuminate\Validation\Rule;

// Assuming $guest is the guest being updated
$guestId = $guest->id;

return [
    'first_name' => 'required|string|max:255',
    'last_name' => 'nullable|string|max:255',
    'other_names' => 'nullable|string|max:255',
    'city' => 'nullable|string|max:255',
    'country' => 'nullable|string|max:255',
    'email' => [
        'required_if:phone,null', 
        Rule::unique('guests')->ignore($guestId)->where(function ($query) use ($request) {
            return $query->where('hotel_id', auth()->user()->hotel_id);
        }),
    ],
    'phone' => [
        'required_if:email,null', 
        Rule::unique('guests')->ignore($guestId)->where(function ($query) use ($request) {
            return $query->where('hotel_id', auth()->user()->hotel_id);
        }),
    ],
    'address' => 'nullable|string|max:255', 
    'other_phone' => 'nullable|numeric:11',    
];

在上面的代码中,

Rule::unique('guests')->ignore($guestId)
告诉 Laravel 强制执行唯一性。

© www.soinside.com 2019 - 2024. All rights reserved.