-4

I'm fairly new to Laravel and looking for the best method for checking whether a model has returned any results or not.

The example below will return null if not results are found. Which is perfect if you only ever want the first result.

$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->first();

The example below will return an object regardless of there being any results.

$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->get();

Therefore i'm currently having to do this every time:

if($results && count($results)) {
     // then do stuff
}

I have methods that call various models and the code looks ugly and inefficient with all of these count() functions.

FYI I'm currently using Laravel 5.1 due to our PHP version (not within my control).

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
steve
  • 471
  • 6
  • 15
  • @ZakariaAcharki thanks but this won't work as the result won't be `null`, it will be an object – steve Aug 14 '18 at 16:32
  • `->get()` combined with `if(count($results) != 0)` should be all you need. `count()` works on a Collection the same way it does on an array. – Tim Lewis Aug 14 '18 at 16:44
  • @TimLewis I clearly haven't got a clue as i'm trying the things suggested but to no avail. I think the issue is with me at this point. I need more experience. Thanks anyway. – steve Aug 14 '18 at 17:20
  • `$results = FooBar::where(['col' => 'someVal', 'col3' => 'value'])->get(); if(count($results) != 0) { // something returned }` shouldn't have any issue, and it's what I use that on a daily basis. Something similar is also suggested in the duplicate, so read that when you can. And don't worry about it, eventually this'll just click. Keep at it. – Tim Lewis Aug 14 '18 at 17:23
  • [`findOrFail()`](https://laravel.com/docs/5.6/eloquent#retrieving-single-models) might be helpful. – Tarasovych Aug 14 '18 at 19:47

1 Answers1

1

You condition is unnecessary too complex, because you cannot do both ->first() and ->get(), therefore you do not need to check both conditions as depending on method you called, one will always be in vein. As you noticed, ->first() can return null - so if you call that method, you check result against null- and I'd suggest doing $result === null instead of using is_null():

if ($result !== null) {
    ...

For calling get() or in general method returning Collection, you will always get it. But it can be empty. In fact, you do not need to know how many results your collection stores. You just need to know if you get at least one, therefore all you need to call is isEmpty() on the collection object:

if (!$collection->isEmpty()) {
  ...

See docs on Collection

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141