Create a new table for a many to many relationship. A User hasMany Rooms. A Room hasMany Users.
Then you should be able to do $user->rooms and $room->users ?
https://laravel.com/docs/5.4/eloquent-relationships#many-to-many
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi,
I'll give an example (not real use case, I made it simplier) to explain my problem. I have 3 tables and 3 models:
User Model
- Id
- Name
- Country
Room Model
- Id
- Capacity
- Level
Booking Model
- Id
- User_id
- Room_id
- Arrival_date
- Departure_date
- etc
For the relations :
One User hasMany Booking
One Room hasMany Booking
One Booking belongsTo a User
One Booking belongsTo a Room
I want to be able from a User to get all the rooms he booked in ($user->rooms) and from a Room all the users that booked it $room->users. I can't use hasManyThrough because I don't have the user_id in the Room for example. Also I think I can use belongsToMany In my User and Room models but Booking is not only a pivot table, it's a normal Eloquent model where I have accessors, other relations, functions, etc. I'm a little stuck, if you have any ideas to create this relations ? I'm on L5.4
Thanks
Please or to participate in this conversation.