Attaching many to many relations while still binding to created event

Posted 3 months ago by chrispage1

So I've run into this issue a few times and now I've decided that I want to find a better solution.

I have two models, Order & Product. There is a many to many relation so that an order can have multiple products. Table structure looks like the below -

orders

  • id
  • more fields...

products

  • id
  • more_fields...

product_orders

  • order_id
  • product_id

So when an order is created I run the following -

$order = Order::create($request->validated())

$order->products()->attach([1,2,3,4...]);

So this does what I want and creates an order record with attached products. However, I want to bind to the Order Created event and get all the linked products in any listeners that may be bound. Problem being, at the time the order created event is fired, the products aren't yet attached. Is there any way to do the above, establishing all the relationships and creating the order at the same time so I can access linked products within the Order Created event listeners?

Thanks, Chris.

Please sign in or create an account to participate in this conversation.