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

dani94's avatar
Level 1

BelongsTo with in memory pivot column

Hey guys!

I dont know if possible... but i would like to create a in memory pivot column.

I have a Booking model with could contains a Coupon:

Booking.php

public function coupon()
    {
        return $this->belongsTo(Coupon::class);
    }

I would like to do something like:

public function coupon()
    {
        return $this->belongsTo(Coupon::class)->using(BookingCoupon::class);
    }

And build BookingCoupon class from booking price in order to calculated the discount price. Right now im doing:

Booking.php has a method which calculate the discount, but I would like to move this class to the relationship. Take in mind i dont want to create a pivot table in database (if i do changes in coupons i dont want to update all database relationships) right now i have 1-N relationship with bookings and coupons tables.

public function discountPrice(): int
    {
        if (! $this->coupon) {
            return 0;
        }

        return min($this->coupon->discountedAmount($this->price), $this->price);
    }

Is it possible ?

0 likes
2 replies
Randy_Johnson's avatar

Am not quite sure how you're doing it but I would do it like this.

public function discountPrice(Request $request) {
	$coupon = Coupon::where('id', '>', $request->coupon_id)->firstOrFail();
	$booking = Booking::where('id', '=', $request->booking_id)->firstOrFail();

	return $item->price - $coupon->discount;
}

But its sometime best to just stick to the resource controllers. So you would have a controller for Booking, Coupon, and when the customer makes the order, you would have a controller called Checkout and inside the checkout using the resource route which would be store you would calculate the discount and have it stored in the Checkout database so it can be seen for future reference, with the coupon reference code and the discount applied.

dani94's avatar
Level 1

@Randy_Johnson

I dont want to persist the discount price, im calculating this. The thing is if is possible to create a in memory relationship attribute.

booking->coupon->discount this should return the discount applied to the booking, and this should be calculated from booking price + coupon logic.

Please or to participate in this conversation.