mercredi 17 avril 2019

Attaching many to many relations while still binding to created event

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

For examples sake, I have two models, Order & Product. There is a many to many relation so that an order can have multiple products and a product can of course have multiple orders. 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 creates an order and attaches the relevant products to it.

However, I want to use an observer, to determine when the order is created and send out and perform related tasks off the back (send an order confirmation email, etc.) The problem being, at the time the order created observer is triggered, the products aren't yet attached.

Is there any way to do the above, establishing all the many to many relationships and creating the order at the same time so I can access linked products within the Order created observer?

Thanks, Chris.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire