Reputation: 496
Trying to check if record
exists in Purchase
class.
When returning $checker
it returns me null
however when I use it inside if else
it gives me Has data
.
Here's my code:
$checker = Purchase::select('id')->where('id',$request->itemid)->get();
if ($checker === null){
echo "None data";
} else {
echo "Has data";
}
Upvotes: 2
Views: 17788
Reputation: 881
Laravel's Query Builder has various aggregate methods, one of which is the exists()
method wherein you can check if a record exists or not.
//returns true or false
$checker = Purchase::select('id')->where('id',$request->itemid)->exists();
Here's the documentation link for reference:
Upvotes: 8
Reputation: 51
How about:
if (isset(Purchase::select("id")->find($request->itemid)->id))
Upvotes: 0
Reputation: 293
Or a ternary:
echo (Purchase::select('id')->where('id',$request->itemid)->exists()) ? "Has Data" : "No Data";
Upvotes: 2
Reputation: 5609
To determine if any records exist that match your query's constraints, you may use the exists and doesntExist methods. It will return true
or false
:
$checker = Purchase::where('id',$request->itemid)->exists();
if ($checker){
echo "Has data";
} else {
echo "None data";
}
Or, you may do the reverse:
$checker = Purchase::where('id',$request->itemid)->doesntExist();
if ($checker){
echo "None data";
} else {
echo "Has data";
}
See the Laravel Documentation: https://laravel.com/docs/6.0/queries#where-exists-clauses
Upvotes: 1
Reputation: 782
You can use
if ($checker ->first()) { }
if (!$checker ->isEmpty()) { }
if ($checker ->count()) { }
if (count($checker )) { }
if ($checker ->isNotEmpty()) { }
You can try any one of these to check and you will get your desired output.
Upvotes: 1