How validate unique email out of the user that is updating it in Laravel?
You can tell that to validators:
'email' => 'unique:users,email_address,'.$user->id
Check the docs, in section 'Forcing A Unique Rule To Ignore A Given ID'.
In Request Class you will probably need this validation in PUT or PATCH method where you don't have user then you can simply 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->id is providing id of the user because $this is object of Request Class and Request also contains 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 it will solve the problem while using request class.
For coders using FormRequest
& Laravel 5.7 and facing this problem, you can do something like this
public function rules() { return [ 'email' => ['required', 'string', 'email', 'max:255', Rule::unique('users')->ignore($this->user), ], ];}
The $this->user
will return the user ID coming from the request.