#Remove a nested item from the collection with the <reject> method

14 messages · Page 1 of 1 (latest)

hard widget
#

Hey there, I'm trying to remove a nested item from a collection using the reject method, but i couldn't get it done, don't know why, here's the code:

$threads = collect([
   [
      'id' => 1, 'subject' => 2, 'participants' => collect([
         ['id' => 1, 'name' => 'John'],
         ['id' => 2, 'name' => 'Doe'],
      ])
   ],
   [
      'id' => 2, 'subject' => 4, 'participants' => collect([
         ['id' => 4, 'name' => 'Foo'],
         ['id' => 2, 'name' => 'Doe'],
      ])
   ],
]);

$filtered = $threads->each->participants->reject(function ($participant) {
   return $participant->id === 2;
});

Thank you for your assistance!

upbeat fractal
#

you are accessing $participant as an object, but they are arrays

#

try ```php
return $participant['id'] === 2;

hard widget
#

but let me try

hard widget
upbeat fractal
#

what do you expect it to output

#

and what is it outputting

chilly sinew
#

What are you trying to remove?

hard widget
chilly sinew
#
$threads = collect([
   [
      'id' => 1, 'subject' => 2, 'participants' => collect([
         ['id' => 1, 'name' => 'John'],
         ['id' => 2, 'name' => 'Doe'],
      ])
   ],
   [
      'id' => 2, 'subject' => 4, 'participants' => collect([
         ['id' => 4, 'name' => 'Foo'],
         ['id' => 2, 'name' => 'Doe'],
      ])
   ],
]);


$filtered = $threads->map(function ($item) {
    return [
        ...$item,
       'participants' => $item['participants']->reject(fn ($item) => $item['id'] === 2)
    ];
})->all();

hard widget
#
$filtered = $threads->map(function ($thread) {
   return [
      ...$thread,
      'participants' => $thread['participants']->reject(
         fn ($participant) => $participant['id'] === auth()->id()
      )
   ];
});
chilly sinew
#

Then your example isn't the same as your actual code