Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Laravel validation rule check a model record exists?

Tags:

laravel

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,

like image 578
softfish Avatar asked Oct 18 '25 10:10

softfish


1 Answers

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...

like image 148
Serge Avatar answered Oct 21 '25 06:10

Serge