6

The main question is how to detect an eloquent collection result is empty or not, what laravel suggest to recognize this?

I have two different questions about this, maybe they are related to each other or not,

The first:

How can i get the result of $result = $user->delete() OR $result = $user->save(); methods?

I mean check if the operation Done or NOT

Is it correct or sufficient to use if($result){...} for this?

The second:

What is the correct way to get $result =User::where(conditions)->get() is empty or not?

Please show me the correct way that cover all cases,

Hamed Yarandi
  • 1,085
  • 1
  • 12
  • 21

4 Answers4

3

Delete and save are synchronous so unless an exception is thrown it's a safe bet they are done.

For the 2nd question, you can do:

User::where(conditions)->count();

There's also isEmpty and isNotEmpty on colllections.

Another way is using exists/doesntExist:

User::where(conditions)->exists(); // or doesntExist()
Brian Lee
  • 17,904
  • 3
  • 41
  • 52
1

1) Yes, it's ok. Or you can use

if($user->delete()) {
  return true;
} else {
  return false;
}

2) You can use function empty()

$result = User::where(conditions)->get()
if (!empty($result)) { 
 // if it is not empty, do the following...
}
IlGala
  • 3,331
  • 4
  • 35
  • 49
1

#1

if($user->delete())
  return true;
    else
  return false;

if($user->save()){
  return true;
}

#2

To determine if there are any results you can do any of the following:

if (!$user->isEmpty()) { }
if ($user->count()) { }
if (count($user)) { }

Notes / References

http://laravel.com/api/5.6/Illuminate/Database/Eloquent/Collection.html#method_first http://laravel.com/api/5.6/Illuminate/Database/Eloquent/Collection.html#method_isEmpty http://laravel.com/api/5.6/Illuminate/Database/Eloquent/Collection.html#method_count http://laravel.com/api/5.6/Illuminate/Database/Eloquent/Collection.html#method_count

DsRaj
  • 2,288
  • 1
  • 16
  • 26
1

First

$user->delete() and $user->save() both are return true or false. So you can do like that.

if($user->save())
    return true;
else
    return false;

Second

According to your statement.

$result = User::where(conditions)->get();    
if(count($result)
     return true;
else
     return false;
Harun
  • 1,137
  • 1
  • 9
  • 7