Warm tip: This article is reproduced from stackoverflow.com, please click
crud laravel

How to Validate Record in Update Case in the Following Critical Situation using Laravel?

发布于 2020-05-14 13:50:06

I want to update record but before update i want to check :- 1. if user exists at time not allowed to update.

Example :-

User jay try to update his name, but user insert same name which is already exists in jay field. at time i want to allow user to update but this code give error that username already exists. What i should do ??

Controller :-

    public function update_data($update_id){

        $gender_list = ['Male', 'Female', 'Other'];
        $country_list = ['India', 'US', 'UK', 'Germany', 'Austraila'];

        $Validator = $this->validate(request(), [
            'username' => 'required|unique:userlists|alpha_num|max:30',
            'email' => ['required', 'unique:userlists', 'email', 'regex:/((yahoo|gmail|hotmail)\.com)/'],
            'password' => 'required',
            'bod' => 'required|after_or_equal:today',
            'comments' => 'required',
            'phone_no' => 'required|numeric',
            'country' => 'required|alpha',
            'gender' => 'required',
            'agreement' => 'required',
        ],[
            'required' => 'Please Enter Your :attribute',
        ]);  

        if(!in_array($request->gender, $gender_list) || !in_array($request->country, $country_list)){

            session()->flash('G_msg', 'Hello Hackes Please Go Back');
            return back();

        }   

       if($Validator->passes()){
                       // updation code.
      }

    }
Questioner
Zobjoys Jeirmov
Viewed
31
Khushbu 2020-03-02 13:10

You can use validation like below:

'username' => ['required','alpha_num', 'max:30',Rule::unique('userlists')->ignore($update_id)]

Make sure Rule is defined above Class:

use Illuminate\Validation\Rule;