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

Sam's avatar
Level 4

Adding different records - relationship

Hi all,

Just need a little sense-check.

So im working on a bookings system and when payment has been made we then add the data to the database, however we allow customers to make multiple bookings via their login etc so we have a Customer model and a Bookings model.

Within the booking I have defined 'customer_id' as a field which references the id on the 'customers' table - ok simple.

My question is, what is the best way of dealing with this in terms of creating the records. Do I:

$new_customer = Customer::create($customer);
$booking = Booking::create($booking);

$booking->customers()->attach($new_customer->id);

Or am I getting this completely wrong?

0 likes
4 replies
Jaytee's avatar

Why not use a belongsToMany relationship instead? Remove that customer_id on the bookings table.

Or if you're already using belongsToMany, change attach to sync()

Attach will attach the id/record but if the order is deleted or cancelled etc, you'll need to detach it. Sync does both of these for you, no duplicates, no nothing.

Sam's avatar
Level 4

Hey @DPJack,

Thanks for jumping in here, just wanting to make sure im setting up my relationship correctly.

A Customer can have many Bookings - So therefor a Customer hasMany Bookings and a Booking belongsTo a Customer?

Surely the above would constitute a one-to-many relationship?

tykus's avatar
tykus
Best Answer
Level 104

The attach and sync methods are for many-to-many relationships, so in your case, you can create the associated record through the relationship:

$customer = Customer::create($customer); // you have a customer object now.
$customer->bookings()->create($booking); // the foreign key is automatically added

This assumes you have a relationship defined on your Customer model as follows:

public function bookings()
{
    return $this->hasMany('App\Booking'); // the foreign key is 'customer_id' by convention
}
Jaytee's avatar

Apologies OP: you could actually use a hasMany relationship. I wasn't thinking properly.

Please or to participate in this conversation.