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

hjortur17's avatar

Inserting into two tables at the same time (many-to-many)

Hi, I need some help figuring out what is the best way to insert into multiple tables at the same time. I did set up many-to-many relationship between my tables and then a single pivot table to connect all of them together. These are my tables: bookings, customers, drivers, and then the pivot table is called booking_pivot.

Inside the Customer and Driver models I have this connection:

public function booking()
{
     return $this->belongsToMany(Booking::class, 'booking_pivot');
}

So in my $request I have information about the booking witch I need to insert into the booking table. Also in the $request, I have information about the customer and driver which has to be placed into there table.

So my question is, what is the best solution to insert these information into the right tables and then somehow link them together in the pivot table. Is my best option to do something like this:

$booking = Booking::create([ ... ]);
$customer = Customer::create([ ... ]);
$driver = Drivers::create([ ... ]);

$booking->customers()->attach(// customer info, is that ID of the customer?);
$booking->drivers()->attach(// drivers info, is that ID of the driver?);

Thanks in advance :)

0 likes
1 reply
Muetze's avatar
Muetze
Best Answer
Level 37

I didn't quite get it, but I'll give it a try.

First create your booking.

$booking = Booking::create([ ... ]);

Then create your relations like

$booking->customers()->create([...]);
$booking->drivers()->firstOrCreate([...])
1 like

Please or to participate in this conversation.