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

_castle21's avatar

Issue with Custom Intermediate Table Models

I migth be overcomplicating things, but this is the eloquent relationships I'm trying to do:

I need to develop a booking app, in which a person can book one or more rooms and each booked room can have one or more services.

So I decided to make a many-to-many relationship between Booking and Room models, (so far this is working as expected). Also in order to link the services to each booked room, I decided to create a many-to-many relationship between the Pivot table resulting from Booking and Room models (booking_room table) and the services table.

It's something like this:

rooms table

id: 5
type: Single Room

----------------------------

id: 7
type: Suite

bookings table

id: 1
name: John Doe
arrival_date: 20180105
departure_date: 20180108

booking_room table

id: 1
booking_id: 1
room_id: 5

---------------------------

id: 2
booking_id: 1
room_id: 7

booking_room_service table

id: 1
booking_room_id: 1     (it's a service for room with id 5)
service_id: 8

--------------------------

id: 2
booking_room_id: 2     (it's a service for room with id 7)
service_id: 9

My question is how do I get the services of a booking_room? I know that I can define Custom Intermediate Table Models, but I'm not sure how to use them.

This is the custom Intermediate model I did in order to fetch the services, but when I call services method, I only get a withTimestamps: false.

use Illuminate\Database\Eloquent\Relations\Pivot;

class BookingRoom extends Pivot
{
    protected $table = 'booking_room';
    protected $fillable = array(
        'booking_id',
        'room_id'
    );

    public function services()
    {
        return $this->belongsToMany('App\Service');
    }

}
0 likes
1 reply
shez1983's avatar

your return $this->belongsToMany('App\Service'); should also include the table you have created booking_room_service table

and then i would have thought it would be easy BookingRoom::with('services')->wheresUserId($user->id):

dont forget to add relationships to BookingRoom for user/rooms

Please or to participate in this conversation.