Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Headpetrol's avatar

Show available options

I am working on a project and need to display available beds in a room. If bed 1 and 2 are taken then it needs to show 3, 4,5. So far I have

      Tables
       Rooms: id, room
       Beds: id, room_id, participant_id

      Models
      Room:  public function beds() { return $this->hasMany(Bed::class); }
      Bed: public function room() { return $this->belongsTo(Room::class); }

      Controller Bed
      public function rooms(Bed $bed)
     {
       $rooms = Room:all();
       $beds = Bed::where('id',$bed->id)->orWhere('bed_id',$bed->id)->get();
     }

    Blade
              @foreach($rooms as $t)
    @foreach($beds as $l)
   @if($t->id == $l->room_id)
   @continue
   @else
   {{ $t->id }}
     @endif  @endforeach @endforeach
 
    Output
   1 2 3 3 4 4 5 5

My goal is to output only 3 4 5, Can someone please help me solve this

0 likes
1 reply
LaryAI's avatar
Level 58

One solution to this problem is to use a subquery to get all the taken bed IDs for a given room, and then use a whereNotIn clause to exclude those IDs from the list of available beds. Here's an example implementation:

// Controller
public function rooms(Bed $bed)
{
    $rooms = Room::all();
    $takenBeds = Bed::where('room_id', $bed->room_id)
        ->whereNotNull('participant_id')
        ->pluck('id');
    $availableBeds = Bed::where('room_id', $bed->room_id)
        ->whereNotIn('id', $takenBeds)
        ->pluck('id');
    return view('rooms', compact('availableBeds'));
}

// Blade
@foreach($availableBeds as $bedId)
    {{ $bedId }}
@endforeach

In this implementation, we first get all the rooms and then use a subquery to get all the taken bed IDs for the given room. We then use a whereNotIn clause to exclude those IDs from the list of available beds, which we return to the view. In the view, we simply loop through the available bed IDs and display them.

Please or to participate in this conversation.