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

hjortur17's avatar

Get only the first of belongsToMany relationship

Hi, I am trying to get only the first customer where the customer belongsToMany bookings. So on my Booking model I have this: (Note that Booking model also have belongsToMany relationship to Car and Driver and I will also try to get the first instance of that because there will only be one car and customer connected to each booking at every time. Each car can not be assigned to many bookings and only one customer can be connected to booking).

public function customer()
{
	return $this->belongsToMany(Customer::class, 'booking_information_pivot');
}

I have tried to add this to the Booking model but that didn't work. Any idea how to make this work? :)

public function getCustomerAttribute()
{
	return $this->customer()->first();
}
0 likes
5 replies
MohamedTammam's avatar

If it it's belongsToMany it means there should be only one customer with the foreign key for the relationship exists.

That part is enough

public function customer()
{
	return $this->belongsToMany(Customer::class, 'booking_information_pivot');
}
$booking->customer
hjortur17's avatar

@MohamedTammam - Sorry, I forgot to mention that I was using Vue and when I try to access the customer there I do have to do booking.customer[0].field, but I would prefer to do it something like this: booking.customer.field

hjortur17's avatar

@Snapey - No havent looked at that but looks nice. Is it possible to have the connection in a pivot table or should I add customer_id to the booking table?

Please or to participate in this conversation.