Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bwrigley's avatar

using Rule::exists for a specific ID

Hi all,

I think I'm missing something here, or perhaps I'm not understanding the docs.

I am trying to add a validation rule in a form request to check that the ID I'm posting already exists in my database. So I thought this would work:

    public function rules(): array
    {

        return [
            'telephoneId' => [
                'required',
                Rule::exists('telephones')->where(function (Builder $query): void {
                    $query->where('id', $this->telephoneId);
                }),
            ],
        ];
    }

but I just get the error The selected telephone id is invalid.

So just to test further I did this:


               Rule::exists('telephones')->where(function (Builder $query): void {

                    $t = Telephone::first();
                    $query->where('id', $t->id);
                }),

same error message.

Have I misunderstood how this works?

0 likes
4 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Just do this

'telephoneId' => [
    'required',
    'exists:telephones,id',
]
Sinnbeck's avatar

Yes by field they mean that the column must have a row with that value :)

Please or to participate in this conversation.