Hi, I am working with Laravel and need to check if a record exists in my database.
$user = User::where('email', '=', $email);
Now how can I check if the user exists?
Hi, I am working with Laravel and need to check if a record exists in my database.
$user = User::where('email', '=', $email);
Now how can I check if the user exists?
There are several ways to check if a record exists in the database.
You can use the exists()
method to check if a record exists.
if (User::where('email', '=', $email)->exists()) {
// user found
}
You can also use the count()
method.
$count = User::where('email', '=', $email)->count();
if ($count > 0) {
// user found
}
Lastly, you can use the first() method, get the first user, and check if it’s empty or not.
$user = User::where('email', '=', $email)->first();
if ($user !== null) {
// user found
}