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:
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.
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
}