2

I am unable to check whether following collection contains data or not

$users = \App\Tempuser::where('mobile','=',$request->mobile)->get();

if(isset($users))
  return "ok";
else
  return "failed";

but if there is nothing in $users still i am not getting else part.

Moppo
  • 18,797
  • 5
  • 65
  • 64
SamD
  • 185
  • 5
  • 22

4 Answers4

4

To check if the collection is empty you can use the isEmpty method:

if( $users->isEmpty() )
  return "collection is empty";
else
  return "collection is not empty";
Moppo
  • 18,797
  • 5
  • 65
  • 64
3

Use something like if ($users->count()) or if (count($users)).

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
2

->get() will always return a collection, you just need to verify whether it contains elements.

if ($users->count())
    return "ok";
else
    return "failed";
Blizz
  • 8,082
  • 2
  • 33
  • 53
0

You can create a macro and put it into your AppServiceProvider

Collection::macro('assertContains', function($value) {
    Assert::assertTrue(
         $this->contains($value)
    );
});

Collection::macro('assertNotContains', function($value) {
    Assert::assertFalse(
        $this->contains($value)
    );
});