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
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.