1 year ago

Attaching many to many relations while still binding to created event

Posted 1 year 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 -


  • id
  • more fields...


  • id
  • more_fields...


  • order_id
  • product_id

So when an order is created I run the following -

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


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.