manoos
manoos

Reputation: 1735

How to check object of a model is empty in laravel?

I am accessing my database using model by using following code.

$persons = WysPerson::where('family_id', $id)->get();

I checked $personsis empty or not by using following code.

if($persons){
        var_dump($persons);
    }

Actually $persons is empty. But I am getting result for var_dump as

object(Illuminate\Database\Eloquent\Collection)#417 (1) { ["items":protected]=> array(0) { } }

How will I check $persons is empty? Can anyone help?

Upvotes: 13

Views: 33238

Answers (5)

Karthik SWOT
Karthik SWOT

Reputation: 1217

You can use isEmpty() method.

At the same time you can check it by simply with count() method before once you fetch the data.

    $count = WysPerson::where('family_id', $id)->count();
    if($count==0){
       return redirect()->back()->withErrors('Empty Data');
     }
    $persons = WysPerson::where('family_id', $id)->get();

Upvotes: 0

Lucas Gervas
Lucas Gervas

Reputation: 379

If you have eloquent collection, call the function isEmpty() like this:

$persons->isEmpty();

This return true or false. Hope this helps.

Upvotes: 4

edwingathige
edwingathige

Reputation: 51

Use the count function

@if (count($persons))

Upvotes: 3

RNEL
RNEL

Reputation: 91

try this.

is_null($var)?abort('empty'):abort('filled') 

Upvotes: 1

Related Questions