kwestionable
kwestionable

Reputation: 496

Laravel 5.8 Eloquent check if record exists

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

Answers (5)

rkg
rkg

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:

  1. From Laravel 5.6 to 7.x
  2. Laravel 8

Upvotes: 8

JohnJohvy
JohnJohvy

Reputation: 51

How about:

if (isset(Purchase::select("id")->find($request->itemid)->id))

Upvotes: 0

Brad Goldsmith
Brad Goldsmith

Reputation: 293

Or a ternary:

echo (Purchase::select('id')->where('id',$request->itemid)->exists()) ? "Has Data" : "No Data";

Upvotes: 2

smartrahat
smartrahat

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

CHARITRA SHRESTHA
CHARITRA SHRESTHA

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

Related Questions