Abhijit Mondal Abhi
Abhijit Mondal Abhi

Reputation: 1829

How to check a collection isEmpty in Laravel?

I am checking a email from DB. The email does not exist. But, how can I check the collection has no matching row? I am using isEmpty() method but it's not working. Don't know why this is happening. Following is my code:

$conflictUser = User::where('email',$newEmail)->get();

if($conflictUser->isEmpty()) {
    abort(409, 'Email Adresse existiert bereits.');
}

I achieved the goal using **count() == 0**. But why isEmpty() is not working that is my question.

Upvotes: 0

Views: 311

Answers (1)

Max Brown
Max Brown

Reputation: 46

Firstwhere:

$conflictUser = User::firstWhere(['email' =>  $newEmail ]) !== null;

First:

$conflictUser = $items->first(function($item) use($newEmail) { 
      return  $item->email === $newEmail;
}) !== null;`

Filter:

$conflictUser = $items->filter(function($item) use($conflictUser) { 
    return $item->emp_id === $needle && $item->dst_id === $needle;
})->count() > 0;

I had this problem and it helped to solve it, I hope it helps

Upvotes: 2

Related Questions