skip to Main Content

I have a problem updating the Laravel account table with its groups. I want Laravel to select that account’s dropdown list ID in the pivot table, but it shows a duplicate dropdown list due to the wrong nested loop. What can I do?

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'));
}

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 relates to the nested loop for the wrong coding technique. Could you please correct me?

2

Answers


  1. 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
    
    Login or Signup to reply.
    • you can use a simpler approach to check if the group is selected. Here’s an updated code of your ‘edit.blade.php’ file
    @foreach($groups as $gr_id => $gr_name)
        <option value="{{ $gr_id }}" {{ $account->group->contains('id', $gr_id) ? 'selected' : '' }}>
            {{ $gr_name }}
        </option>
    @endforeach
    
    • contains(‘id’, $gr_id) checks if the current group ID is present in the collection of selected groups
    • If true, it adds the ‘selected’ attribute to the option, indicating that it should be pre-selected
    • This should help you avoid duplicates and simplify your code.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search