编辑现有用户时如何忽略 laravel 验证某些列

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

我正在尝试更新客人信息,但如果没有更改正在更新的客人的详细信息,我想忽略电话和电子邮件。但在创建新来宾时,应该对唯一性进行适当的检查。我怎样才能做到这一点。请各位兄弟帮忙。我已经面对这个问题很久了。

以下是我的表单验证规则

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.