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

lawiszxc's avatar

How to create relationship 😞

Between: Users, Booking, and Pay

0 likes
5 replies
Sinnbeck's avatar

How are they related? A user HasMany bookings? A booking belongsTo a user (hint hint) :)

dysentry30's avatar

If the User has many Bookings, you can use $this->hasMany(), or use $this->hasOne() if the user just have only 1 Booking. It depends on how your table and relation works.

Lara_Love's avatar

Hello my friend If I get it right, you have established the many-to-many-relationships between every two of the three models (User, Booking & pay). Instead, you should establish the many-to-many between any two models of your choice and treat the third model as a pivot. For example:

User.php

class User extends Model
{
public function Bookings()
{
return $this->belongsToMany(Booking::class)->withPivot('pay');
}}

Booking.php

class Booking extends Model
{
public function Users()
{
return $this->belongsToMany(User::class)->withPivot('pay');
} }

view.blade.php

@foreach($Users as $User)
@foreach($User->Bookings as $book)
{{ $book->name }} {{ $book->pivot->pay }}
@endforeach
@endforeach
Tray2's avatar

@LoverCode This is a bad advice

@foreach($Users as $User)
   @foreach($User->Bookings as $book)
      {{ $book->name }} {{ $book->pivot->pay }}
   @endforeach
@endforeach

This will introduce a n+1 issue, the bookings should be eager loaded in the controller. Another problem is that a vairable always should start with a lower case letter, not an upper case letter. Classes should start with a upper case letter.

Please or to participate in this conversation.