Home > Mobile >  Laravel - How to reassign an array inside a collection? or how to group an array inside a collection
Laravel - How to reassign an array inside a collection? or how to group an array inside a collection

Time:11-30

I have a collection of lists, each List has an array of items. I need to group items by id on each list.

When I try to reassign $list->items, nothing happens, but if I reassign $list->name, it works, so the problem is arrays or arrays properties of an object, or something like that...

What do I have to do to reassign an array inside a collection?

    $lists = Listt::with('items')->get();
    $newLists = $lists->map(function(Listt $list) {

        // $list->items = $list->items->groupBy('id'); // this is what I want, it doesn't work
        // $list->items = []; // this doesn't work either
        // $list['items'] = []; // nope
        // $list->items = new Collection(); // nope
        $list->items = collect([... $list->items])->groupBy('id');// nope

        $list->name = 'test'; //this works, so the problem is arrays <----

        return $list;
    });
    return $newLists;

    /* transform doesn't work */
    // $lists->transform(function(Listt $list) {
        //... 
    // });
    // return $lists;

    /* this, from a similar question, doesn't work either, besides I don't understand it and it doesn't use collection methods... */
    // foreach($lists as &$list){
    //    $list['items'] = [];
    //    unset($list);
    // }
    // return $lists;

CodePudding user response:

Because items is already a relationship, I don't really want to reuse that as an attribute.

I suggest you assign the grouped by items to a new attribute on each list. I names that grouped_items:

return List::with('items')
    ->get()
    ->each(function ($list) {
        $list->grouped_items = $list->items->groupBy('id');
    });

If you insist on assigning to items. you can still do so but I don't recommend this:

return List::with('items')
    ->get()
    ->each(function ($list) {
        $items = $list->items;

        // This step might not be necessary.
        $list->unsetRelation('items');

        $list->setRelation('items', $items->groupBy('id'));
    });
  • Related