Home > Net >  How to ignore the value of an existing column stored in the database in an update form?
How to ignore the value of an existing column stored in the database in an update form?

Time:12-31

In my update form, the passport field receives the value of its record, but when I confirm the form the unique validation points out that this value is already repeated, and is only valid when I change the value, I don't want to do that I want this validation to be ignored if the value remains unchanged.

I use the same JudokaRequest.php class in the store() and update() methods.

  • JodokaRequest.php

    public function rules()
    {
       return [
          'passaport' => ['required','size:8','unique:judokas,passaport', new PassportNumberRule],
       ];
    }
    
    public function messages()
    {
       return [
          'passaport.unique' => 'The passport number is already registered, repeated passport values are not accepted.',
       ];
    }

CodePudding user response:

You can use the Illuminate\Validation\Rule so that you can add a condition on whether to ignore the validation rule for the given model.

Usage

return [
    'passaport' => [
        'required',
        'size:8',
        Rule::unique('judokas','passaport')->ignore(the instance of model you are editing), // if you are using the Route-Model Binding you can just refer the model using `$this->yourModel` 
        new PassportNumberRule,
    ],
];

CodePudding user response:

Try this:

return [
   'passaport' => [
       'size:8',
       'required',
       Rule::unique('users')->ignore($user->passaport),
   ],
];

By ->ignore() method we want Laravel to ignore the specified value (e.g. $user->passaport).

For more info you can take a look at Laravel documentation.

  • Related