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

extjac's avatar

Get Revenue - Event > Bookings > Booking Lines

I would like to be able to have an "Event Revenu" relationship.

Right now I can use $bookings->revenu(), but when I trying $event->bookings->revenu() it does not work.

# Event Model
- Id
- EventName
public function bookings()
{
    return $this->hasMany( '\App\Booking', 'event_id' );
}


# Booking Model
- id
- EventID

public function event()
{
        return $this->belongsTo('App\Event');
}

public function lines()
{
    return $this->hasMany('App\BookingLine', 'booking_id');
}

public function revenu()
{
    return $this->lines->sum('price') ;
}


# BookingLine Model
- Id
- BookingId
- Price
- Quantity
public function booking()
{
    return $this->belongsTo('App\Booking', 'booking_id');
}
0 likes
2 replies
tisuchi's avatar

@extjac

It's because of your event and bookings has one to many relationships.

Since it's one to many, in your query, you have use in the loop or get on the first item.

For example,

$event->bookings[0]->revenu() 

Or

foreach($event->bookings as $booking) {

	echo $booking-revenu();

}
extjac's avatar
extjac
OP
Best Answer
Level 6

I managed to do it by using hasManyThrough

Event Model

    public function revenue()
    {
        return $this->hasManyThrough(
            'App\BookingLine',  // event has many lines
            'App\Booking',  // Through bookings
            'event_id',      // the Foreign key on Booking table that point to Model
            'booking_id'   // Foreign key on booking_lines table
        );
    }

then I can do $event->revenue->sum('price');

Please or to participate in this conversation.