Laravel validation: exists with additional column condition - custom validation rule

Jonathon picture Jonathon · Sep 30, 2014 · Viewed 95.2k times · Source

Is there is a way of referencing another field when specifying the exists validation rule in Laravel? I want to be able to say that input a must exist in table a, input b must exist in table b AND the value for column x in table b must equal input a.

Best explained by example:

public $rules = array(
    'game_id' => 'required|exists:games,id',
    'team1_id' => 'required|exists:teams,id,game_id,<game_id input value here>',
    'team2_id' => 'required|exists:teams,id,game_id,<game_id input value here>'
);

So with my validation rules I want to be able to make sure that:

  • game_id exists within the games table (id field)
  • team1_id exists within the teams table (id field) and the game_id column (in the teams table) must equal the value of the game_id input.
  • As above for team2_id

So, if in my form, I entered 1 for game_id, I want to be able to ensure that the record within the teams table for both team1_id and team2_id have the value 1 for game_id.

I hope this makes sense.

Thanks

Answer

roerjo picture roerjo · Jun 15, 2017

From Laravel 5.3+ you can add a custom where clause to the exists and unique rules.

Here is my scenario: I have an email verification table and I want to ensure that a passed machine code and activation code exist on the same row.

Be sure to use Illuminate\Validation\Rule;

$activationCode = $request->activation_code;                                   

$rules = [                                                                     
    'mc' => [                                                                  
        'required',                                                            
        Rule::exists('email_verifications', 'machineCode')                     
        ->where('activationCode', $activationCode),                                                                    
    ],                                                                         
    'activation_code' => 'required|integer|min:5',                             
    'operating_system' => 'required|alpha_num|max:45'                          
];

The first argument in the exists method is the table and the second is the custom column name I'm using for the 'mc' field. I pass the second column I want to check in a where clause.

This is pretty handy, because now I no longer need a custom Validation rule.