softfish
softfish

Reputation: 53

Can Laravel validation rule check a model record exists?

I am having trouble to understand how the Laravel exists validation works in term of checking the existing record in the database.

e.g.

POST request with user.id = 1

is that possible to use validation rule: 'id' => 'exists:users' to check the user 1 existed in the users table?

Any good example will be good.

Thanks,

Upvotes: 4

Views: 13592

Answers (1)

Serge
Serge

Reputation: 2187

Exist will check for existence ... for example, if you want to make sure the state exists in the state table...

If you want to have a unique entry (check for existance and fail if it already exists) you need to use unique...

    $request->validate([
        'id' => 'required|unique:users',
// .    'id' => 'required|exists:App\User,id', This works laravel 6 and up
        'body' => 'required',
    ]);

In this case, we check that the id is unique in the user table... you could specify unique for any field... providing 'unique:table,field name',. This will fail validation on duplicates...

Updated the answer to reflect excellent comments from @mafortis and @alexkb...

Upvotes: 11

Related Questions