Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to validate a foreign key using Laravel's Validation syntax?

Say I have an object which relates to a mission. Users can upload objects and say that it has a relationship with one of these missions. Is there anyway to check that the mission_id that the user has selected for this object actually exists in this database using Laravel's Validation class and rules?

This way, I can check that mission_id is not only an integer, but also exists in the database.

For example, I guess I'm looking for something like:

$rules = array(     'mission_id' => 'foreignKeyExistsInMissions|integer' ) 

Where foreignKeyExistsInMissions is the validation rule I'm looking for.

like image 295
marked-down Avatar asked Apr 13 '15 17:04

marked-down


Video Answer


1 Answers

This should work:

'mission_id' => 'required|exists:missions,id', 

And the message:

'mission_id.exists' => 'Not an existing ID', 

Source (v4.2 docs)

Source (v5.5 docs)

Source (v7.x docs)

Source (v8.x docs)

like image 131
Jeff Lambert Avatar answered Sep 27 '22 23:09

Jeff Lambert