I am having problem with update Laravel account table with its groups.I want laravel to select the dropdown list id that that account has in the pivot table but it show duplicate dropdown list due the wrong nested loop. how can I do?

in Account Controller

    public function edit(string $id)
        {
            $account = Account::find($id);
            $groups = Group::pluck('name','id')->toArray();
            $pages = Page::pluck('name','id')->toArray();
            return view('accounts.edit',compact('account','groups','pages'));
        }

in edit.blade.php

    @foreach( $groups as $gr_id => $gr_name ) /** Get all data from db to show in html dropdown **/

        @foreach ($account->group as $group_data)  /** get the selected dropdown from pivot table **/ 

            @if ( $gr_id == $group_data->id ) /** compare their id the selected dropdown **/
                <option value="{{ $gr_id }}" selected> {{ $gr_name }}</option>
            @else 
                <option value="{{ $gr_id }}"> {{ $gr_name }}</option>
            @endif  

        @endforeach 

    @endforeach
                

This issue is relates to the nested loop for wrong coding technique. Could you please correct me?

New contributor

Heng Vanna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Try looping through all groups once and then check if the current group is in the account’s groups. You can achieve this by using the contains method provided by Laravel’s collections.

@foreach( $groups as $gr_id => $gr_name )
    @if ($account->group->contains('id', $gr_id))
        <option value="{{ $gr_id }}" selected> {{ $gr_name }}</option>
    @else 
        <option value="{{ $gr_id }}"> {{ $gr_name }}</option>
    @endif
@endforeach