Rich
Rich

Reputation: 185

Laravel validation rule with unique and compare with another column

I need a bit of help here

This is my user table. I want to write a laravel validation rule like there should be only one user for one group_id. For example, another entry with the name John and group_id=1 should give The name has already been taken. error, but should insert john with group_id=2.

*************************** 1. row ***************************          
        id: 1
      name: jhon
  group_id: 1
created_at: 2021-05-31 10:23:42
updated_at: 2021-05-31 10:23:42
*************************** 2. row ***************************
        id: 2
      name: michele
  group_id: 2
created_at: 2021-05-31 10:23:42
updated_at: 2021-05-31 10:23:42

I have tried like below, but it is not working. Can anyone help me out?

'user.name' => ['required','unique:user,name'.$this->user->id,Rule::unique('user')->where(function ($query) {
    return $query->where('group_id', $this->user->group_id);
})],

Upvotes: 0

Views: 776

Answers (1)

John Lobo
John Lobo

Reputation: 15319

You can write custom validation for that

'user.name' => ['required',function ($attribute, $value, $fail) {
                      
   $user= User::where(function ($query){
                            $query->where('name',$this->name);
                            $query->where('group_id',$this->group_id );
                        })->exists();
                        
                    
                       if($user){
                           $fail('User with group already exist');
                       }
                    }],

You can ref official documentation

https://laravel.com/docs/8.x/validation#using-closures

Updates

 'user.name' => ['required',function ($attribute, $value, $fail) {
                          
       $user= User::where(function ($query){
                              $query->where('id','!=',$this->user->id)
                                $query->where('name',$this->user->name);
                                $query->where('group_id',$this->user->group_id );
                            })->exists();
                            
                        
                           if($user){
                               $fail('User with group already exist');
                           }
                        }],

Upvotes: 1

Related Questions