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

Givar's avatar
Level 1

How can i get the box id when querying a many to many relation in laravel?

I'm building a smart lockers building system and I'm just facing an issue that i don't really know how to solve. Let me explain, my db for this particular operation has 3 tables that are interested, where one is a pivot table:

box
reservations
box_reservation

between box and reservations there's a many to many relation because :

one box belongsToMany reservations
one reservation can belongToMany boxes

When checking availability i need to return the box_id that are booked for the period requested so that, if there's availability, i can later assign a new box id to the newly made reservation.

Following there's the code in my controller, the function create() is called when submitting the check availability form, while the store() is to create the instances.

    //Controllo la disponibilità dei box per le date e gli orari richiesti e prendo gli ID dei box prenotati nel periodo
    $reservedBoxId = Reservation::orWhere(function ($q1) use ($beginningDateTime, $endDateTime) {
       $q1->where('beginning_date_time', '>=', $beginningDateTime )
          ->where('beginning_date_time', '<=', $endDateTime);

    })
    ->orWhere(function ($q2) use ($beginningDateTime, $endDateTime) {
       $q2->where('end_date_time', '>=', $beginningDateTime )
          ->where('end_date_time', '<=', $endDateTime);
    })
    ->orWhere(function ($q3) use ($beginningDateTime, $endDateTime) {
       $q3->where('beginning_date_time', '>=', $beginningDateTime)
          ->where('end_date_time', '<=', $endDateTime);
    })
    ->orWhere(function ($q4) use ($beginningDateTime, $endDateTime) {
       $q4->where('beginning_date_time', '<=', $beginningDateTime)
          ->where('end_date_time', '>=', $endDateTime);
    })
    ->select('box_id')->get()->pluck('box_id');//I tried to do, but OBVIOUSLY, it doesn't work because that column is not inside the reservation table.

    

The problem with the code is in the create() method when quering the DB.

The problem is, being the box_id in a different table, how do iget the box_id tied to the reservations already active in that period???

Does anybody have an idea?

Thank you

0 likes
2 replies
Givar's avatar
Level 1

@MichalOravec thank you very much for helping me out! This has really solved my problems and thanks to you I learned something new.

1 like

Please or to participate in this conversation.