Search code examples
laravelfiltercollections

Laravel Collection - Remove Object containing empty array


I have an Collection of objects - some of which contain empty arrays.

object(Illuminate\Support\Collection)#34225 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Support\Collection)#34226 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Support\Collection)#34227 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Support\Collection)#34228 (1) {
  ["items":protected]=>
  array(0) {
  }
}
object(Illuminate\Database\Eloquent\Collection)#23760 (1) {
  ["items":protected]=>
  array(2) {
    [0]=>
    object(App\Models\File)#23766 (27) {
      ["primaryKey":protected]=>
      string(6) "FileID"
      ["table":protected]=>

I could use someones help in filtering the Collection of objects so that the objects containing empty arrays are gone/removed.

So that all that remains are the objects with non empty arrays

object(Illuminate\Database\Eloquent\Collection)#23760 (1) {
  ["items":protected]=>
  array(2) {
    [0]=>
    object(App\Models\File)#23766 (27) {
      ["primaryKey":protected]=>
      string(6) "FileID"

I have populated the collection using

 $things = $foos->get($thing->ID, collect());

Any help would be greatly appreciated


Solution

  • You may convert it to an array using toArray() method

    $things = $foos->get($thing->ID, collect())->toArray();
    
    foreach($things as $thing) {
       if(empty($thing['items'])) {
           unset($thing);
       }
    }
    
    $things = array_values($things);
    

    Or

    Using filter()

    The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

    $things = $foos->get($thing->ID, collect());
    
    $filtered = $things->filter(function ($value, $key) {
        return !empty($value->items) ;
    });
    
    $result = $filtered->all();