SamD
SamD

Reputation: 337

How to check if collection contains a value in Laravel

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.

Upvotes: 2

Views: 3788

Answers (4)

Denis Mitrofanov
Denis Mitrofanov

Reputation: 5

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)
    );
});

Upvotes: 0

Moppo
Moppo

Reputation: 19285

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";

Upvotes: 4

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

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

Upvotes: 3

Blizz
Blizz

Reputation: 8400

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

if ($users->count())
    return "ok";
else
    return "failed";

Upvotes: 2

Related Questions