I know this question has been asked many times before but no one explains how to get the id when you're validating in the model.
'email' => 'unique:users,email_address,10'
My validation rule is in the model so how do I pass the ID of the record to the validation rule.
Here is my models/User
protected $rules_update = [ 'email_address' => 'required|email|unique:users,email_address,'.$id, 'first_name' => "required", 'last_name' => "required", 'password' => "required|min:6|same:password_confirm", 'password_confirm' => "required:min:6|same:password", 'password_current' => "required:min:6" ];
models/BaseModel
protected $rules = array(); public $errors; /* * @data: array, Data to be validated * @rules: string, rule name in model */ public function validate($data, $rules = "rules") { $validation = Validator::make($data, $this->$rules); if($validation->passes()) { return true; } $this->errors = $validation->messages(); return false; }
you can add unique validation on update request class. Sometime we need to add unique validation on update for email, username etc. at that time if you check unique email or username then you have to write database query manually and do it using if condition.
'email' => 'required|email|unique:users,email_address,'. $id . '' In model update method, for exemple, should receive the $id with parameter.
Just a side note, most answers to this question talk about email_address
while in Laravel's inbuilt auth system, the email field name is just email
. Here is an example how you can validate a unique field, i.e. an email on the update:
In a Form Request, you do like this:
public function rules() { return [ 'email' => 'required|email|unique:users,email,'.$this->user->id, ]; }
Or if you are validating your data in a controller directly:
public function update(Request $request, User $user) { $request->validate([ 'email' => 'required|email|unique:users,email,'.$user->id, ]); }
Update: If you are updating the signed in user and aren't injecting the User
model into your route, you may encounter undefined property when accessing id
on $this->user
. In that case, use:
public function rules() { return [ 'email' => 'required|email|unique:users,email,'.$this->user()->id, ]; }
A more elegant way since Laravel 5.7 is:
public function rules() { return [ 'email' => ['required', 'email', \Illuminate\Validation\Rule::unique('users')->ignore($this->user()->id)] ]; }
P.S: I have added some other rules, i.e. required and email, in order to make this example clear for newbies.
One simple solution.
In your Model
protected $rules = [ 'email_address' => 'sometimes|required|email|unique:users', .. ];
In your Controller, action:update
... $rules = User::$rules; $rules['email_address'] = $rules['email_address'] . ',id,' . $id; $validationCertificate = Validator::make($input, $rules);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With