I'm currently trying to create an index of cards depicting rooms, with their associated desks indexed within them, using nested foreach loops within the view:
<div class="grid grid-cols-1 gap-3 ">
@foreach ($rooms as $room)
<div class="bg-white text-center h-auto">
{{ $room->name }}
<div class="m-3">
<div class="lg:grid lg:grid-cols-6 gap-3">
@foreach ($desks as $desk)
<div class="bg-red-200 text-center h-10">
Desk {{ $desk->id }}
</div>
@endforeach
</div>
</div>
</div>
@endforeach
</div>
The Room controller index action currently looks like this:
class RoomController extends Controller
{
public function index()
{
return view('index', [
'rooms' => Room::all(),
'desks' => Desk::all()
]);
}
}
I'm aware that Desk::all() is indexing all desks for all rooms. Instead, I need to build a query that indexes desks belonging only to each room. My model relationships are defined as:
Room hasMany desks
Desk belongsTo room
Any help would be much appreciated, thanks.