Laravel check if a record exists or not with example
In this article, I will show you how you can check if record exists or not before inserting to database. This is important to check otherwise it will create duplicate records error. Like username, email should ne unique in database.
There are many ways you can check if the records exists or not. We will discuss all the ways to check it. So let's start:
first() method
Prior to Laravel 7, the first() method was used to check if the record exists or not. This method returns the first records from the database. You can use this method to check whether the record exists or not.
/**
* Display a instance of the resource.
*
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
$user = User::where('email', $request->email)->first();
if ($user != null) {
echo("Email exists");
} else {
echo("Email not exists");
}
}
exists() method
If you only want to check whether record exists or not and you don't want to get record, then exists() method is used. This method return boolean value. If the record exists, it will return true, else return false.
/**
* Display a instance of the resource.
*
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
$user = User::where('email', $request->email)->exists();
if ($user) {
echo("Email exists");
} else {
echo("Email not exists");
}
}
doesntExist() method
On the contrary, if you want reverse check, then you can use doesntExist() method. This will return true if record doesn't exists.
/**
* Display a instance of the resource.
*
* @return \Illuminate\Http\Response
*/
public function show(Request $request)
{
$user = User::where('email', $request->email)->doesntExist();
if ($user) {
echo("Email not exists");
} else {
echo("Email exists");
}
}
Thank you for giving time in reading article. I hope you liked this article and help you.
Copyright 2023 HackTheStuff