27
votes

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.

3

3 Answers

62
votes

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)

0
votes

'mission_id' => 'required|exists:missions,id', missions is the table name and id is the referenced column name on mission table ''mission_id' => 'required|exists:table_name,referenced_column',

0
votes
<?php

namespace App\Http\Requests\Leave\LeaveAssigns;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreLeaveAssignRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'role_id' => ['required', Rule::exists('roles', 'id')]
        ];
    }
}