How to check the unique email address of a user who updates it in Laravel?

I am using Laravel 5.2 and want to update a user account using a validator.

I want the email field to be unique, but if the user types their current email address, it will break. How can I update if the email is unique, except that the user has a current email?

+5
source share
2 answers

This can be checked for validators:

'email' => 'unique:users,email_address,'.$user->id 

Check the docs in the section "Enforcing a unique rule to ignore the given identifier".

+14
source

In the query class, you probably need this check in the PUT or PATCH method, where you don't have a user, then you can just use this rule

  You have 2 options to do this 

1

  'email' => "unique:users,email,$this->id,id" 

OR

2:

  use Illuminate\Validation\Rule; //import Rule class 'email' => Rule::unique('users')->ignore($this->id); //use it in PUT or PATCH method 

$ this-> identifier provides the user identifier, since $ this is an object of the request class and the request also contains the user object.

 public function rules() { switch ($this->method()) { case 'POST': { return [ 'name' => 'required', 'email' => 'required|email|unique:users', 'password' => 'required' ]; } case 'PUT': case 'PATCH': { return [ 'name' => 'required', 'email' => "unique:users,email,$this->id,id", OR //below way will only work in Laravel ^5.5 'email' => Rule::unique('users')->ignore($this->id), //Sometimes you dont have id in $this object //then you can use route method to get object of model //and then get the id or slug whatever you want like below: 'email' => Rule::unique('users')->ignore($this->route()->user->id), ]; } default: break; } } 

Hope this solves the problem when using the query class.

+1
source

Source: https://habr.com/ru/post/1260742/


All Articles