phplaravellaravel-formrequest

Email Already Taken, When update Laravel 8


Heloo friend im dwi prihtapambudi, i using form request on laravel 8 to create validation, in the validation i have validation unique type on email, i try update data but i have error "email already taken" can sombody help me please

this is my model

 protected $fillable = [
        'name',
        'email',
        'password',
    ];

this is my controller

   public function store(UserRequest $request)
    {
        $data=$request->All();
        $data['password'] = Hash::make($request->password);
        User::updateOrCreate(['id'=>$request->id],$data);
        return response()->json($data);
    }

and this is my validation

  public function rules()
    {
        return [
            'name'=>'required|string|min:1|max:60',
            'email'=>'required|string|email|unique:users|max:255',
            'password'=>'required|string|min:6',
            'password_confirm' => 'required|same:password',
        ];
    }

thanks for your atenttion guyss


Solution

  • while updating ignore editing user record row from unique validation

      'email'=>'required|string|email|max:255|unique:users,email,'.$this->id,
    

    Updated:

    <?php
    
    namespace App\Http\Requests;
    
    use Illuminate\Foundation\Http\FormRequest;
    
    class UserRequest  extends FormRequest
    {
    
       private $defaultValidation=[];
        public function authorize()
        {
            return true;
        }
    
    
        public function rules()
        {
            $this->defaultValidation=[
                'name'=>'required|string|min:1|max:60',
                'email'=>'required|string|email|max:255|unique:users,email,'.$this->id,
            ];
            
            if(empty($this->id)){
                $this->defaultValidation['password']='required|string|min:6';
                $this->defaultValidation['password_confirm']='required|same:password';
            }
    
    
            switch ($this->method()) {
    
                case 'POST':
                    return   $this->defaultValidation;;
                default:
                    break;
            }
            return [];
        }
    
    
    }