MB
1 month ago
272
3
Laravel

Collection forget() method does not remove items

Posted 1 month ago by MB

Hi,

Why does this not remove the "item/id" from the collection? The foreach loop keep grabbing the value.

Code:

@php
    # Flattern multidimensional collection, so (new) collection only contain Item ID's
    $sr_itemss = $character->softreserves->pluck('item_id')->flatten();
@endphp

@for ($i = 0; $i < $maxselects; $i++)

    <label for="itemInput{{$i}}">SR #{{ $i+1 }}</label>
    <select class="" id="itemInput{{$i}}" name="softreserves[]">

        <option selected></option>
        @foreach($items as $item)

            @php

                if($sr_itemss->contains($item->id)) {

                    $selected = 'selected';

                    # Remove Item ID from collection
                    $sr_itemss->forget($item->id);

                }else{
                    $selected = '';
                }

            @endphp

            <option value="{{ $item->id }}" {{ $selected }}>{{ $item->name }}</option>

        @endforeach

    </select>

@endfor

Collection:

echo $sr_itemss; ["18703","16811"]


//The collection is also likely to have the same number multiple times.:

["15478","62457","15478"]

// in which case it should only remove one of the numbers from the collection. Not sure if forget() will remove both of them, since I never got it to work.

My idea is to remove the item from the collection after each run, but something is wrong. It keep selecting the same option for all the select inputs.

Any help would be much appreciated.

, Kenneth.

Please sign in or create an account to participate in this conversation.