Search code examples
phpvalidationlaravel

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.


Solution

  • 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)