Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 447
manoos Avatar asked Apr 14 '15 11:04

manoos


People also ask

How do you check PHP object is empty or not?

Using empty() won't work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared. Therefore you can use count() (if the object is Countable). Or by using get_object_vars() , e.g.


4 Answers

You can use the isEmpty method:

http://laravel.com/api/5.0/Illuminate/Support/Collection.html#method_isEmpty

like image 189
Angel Iliikov Avatar answered Oct 04 '22 03:10

Angel Iliikov


Use the count function

@if (count($persons))

like image 41
edwingathige Avatar answered Oct 04 '22 03:10

edwingathige


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

$persons->isEmpty();

This return true or false. Hope this helps.

like image 32
Lucas Gervas Avatar answered Oct 04 '22 02:10

Lucas Gervas


try this.

is_null($var)?abort('empty'):abort('filled') 
like image 43
Michael Mendoza Avatar answered Oct 04 '22 02:10

Michael Mendoza