13

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?

manoos
  • 1,675
  • 3
  • 21
  • 46
  • @Naruto collections are not arrays. isEmpty is the right method as answered below by Angel – Merhawi Fissehaye Apr 14 '15 at 11:16
  • Possible duplicate of [Eloquent collection: counting and detect empty](http://stackoverflow.com/questions/20563166/eloquent-collection-counting-and-detect-empty) – Gary Green Nov 23 '16 at 10:54
  • The title is misleading. "Object of a model is empty" implies whether an instance of `\Illuminate\Database\Eloquent\Model` has no attributes set (which is why I'm in here). You're really asking whether the collection returned by a `get` operation on a model is empty. – Jay Bienvenu Jan 18 '23 at 22:16

5 Answers5

16

You can use the isEmpty method:

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

Angel Iliikov
  • 710
  • 5
  • 8
4

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

$persons->isEmpty();

This return true or false. Hope this helps.

DanielBarbarian
  • 5,093
  • 12
  • 35
  • 44
Lucas Gervas
  • 369
  • 2
  • 5
3

Use the count function

@if (count($persons))

  • there is an issue with your answer, if you forgot to execute the query with ->get() and just leave the query in place count will return 1. isEmpty will throw an exception which in the grand scheme of things is better. – Cptmaxon Dec 15 '15 at 09:30
  • And checking collection count wont work, till it's Laravel collection – Sigismund Jun 17 '16 at 10:40
1

try this.

is_null($var)?abort('empty'):abort('filled') 
Michael Mendoza
  • 91
  • 1
  • 2
  • 10
0

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();
Karthik SWOT
  • 1,129
  • 1
  • 11
  • 15