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

yonka's avatar
Level 2

Save Multiple Child Data at once after checking Quantity

I have Three Tables: Inventory, SoldInventoryItems, SoldInventoryInfo. SoldInventoryInfo has many SoldInventoryItems. SoldInventoryItems belongsTo Inventory and SoldInventoryInfo. Inventory hasMany SoldInventoryItems. I want to save many SoldInventoryItems at once after checking their Quantity in Inventory. If The Quantity of one of the SoldInventoryItems I want to save is less than Quantity in Inventory, I want not save the rest untill they all pass.

0 likes
3 replies
LaryAI's avatar
Level 58

To achieve this, you can use a transaction to ensure that all operations are completed successfully before committing the changes to the database. If any of the conditions fail, you can roll back the transaction to maintain data integrity. Here's a step-by-step solution using Laravel's Eloquent ORM:

  1. Start a Database Transaction: Use Laravel's DB::transaction method to ensure atomicity.

  2. Check Inventory Quantities: Loop through the items you want to sell and check if each item's quantity is available in the inventory.

  3. Save SoldInventoryItems: If all items have sufficient quantity, save them to the SoldInventoryItems table.

  4. Rollback if any condition fails: If any item does not have sufficient quantity, rollback the transaction.

Here's a code example to illustrate this:

Explanation:

  • Transaction: The DB::transaction method ensures that all database operations within the closure are executed as a single unit. If any operation fails, the transaction is rolled back.

  • Inventory Check: Before saving any SoldInventoryItem, we check if the inventory has enough quantity. If not, an exception is thrown, which automatically triggers a rollback.

  • Saving and Updating: If all checks pass, we save each SoldInventoryItem and update the inventory quantities accordingly.

This approach ensures that either all items are saved successfully, or none are saved, maintaining the integrity of your data.

1 like
yonka's avatar
Level 2

When New Exception is thrown, I want to display Error Message like Flash message but How?

Please or to participate in this conversation.