4
votes

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,

4
For the first, always consult the API documentation or PHPDoc block. It should say what return type/value to expect.Devon

4 Answers

1
votes

#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

1
votes

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()
1
votes

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;
1
votes

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...
}