How to check if a record exists in Laravel

Published June 25, 2021

Laravel uses Eloquent, an object-relational mapper (ORM) that makes it very easy to interact with the database to determine if a record exists.

Using first()

If you need to use the object if it exists and is returned by the database query, you can use first().

$user = User::where('email', $request->email)->first();
if ($user === null) {
  // user does not exist
}

Using count()

If you don't need to use the object, and only need to check if such a record exists in the database, you can use count().

if (User::where('email', $request->email)->count() > 0) {
  // user exists
}

Using exists()

There is also an exists() function that can be used to further simplify the query.

if (User::where('email', $request->email)->exists()) {
  // user exists
}