Skip to content
Advertisement

laravel id value changed after adding a nested loop

I used the following code to display the role of the user however, when I want to edit or delete it leads me to the deleted ids number 2/3 it return the same thing even when I change the for else with foreach Attempt to read property "id" on null (View: C:laravelgautoresourcesviewsdashboarduseredit.blade.php)! when I delete the nested foreach loop everything back to normal thank you in advance

                            @forelse($users as $item)
                                <tr>
                                    <td>{{ $loop->iteration }}</td>
                                    <td>{{ $item->name }}</td>
                                    <td>{{ $item->email }}</td>
                                    <td>
                                        @if($item->email_verified_at)
                                            {{ "verified" }}
                                        @else
                                            {{ "not verified" }}
                                        @endif
                                    </td>
                                    <td>    
                                        @foreach($item->roles as $item)
                                            {{ $item['name'] }} 
                                        @endforeach
                                    </td>
                                    <td>
                                        <a href="{{ route('user.edit', $item->id) }}">Edit</a>
                                        <form action="{{ route('user.destroy', $item->id) }}" method="POST">
                                            @csrf
                                            @method('delete')
                                            <button onclick="return confirm('Are you sure ??')" type="submit">Delete</button>
                                        </form>
                                    </td>
                                </tr>
                                @empty
                                <tr>
                                    blank data
                                </tr>
                            @endforelse

Advertisement

Answer

Your users are also saved in $item and in the loop you are allocating $item a different value every time.

Try changing the code to

<td>    
      @foreach($item->roles as $role)
           {{ $role['name'] }} 
      @endforeach
</td>

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement