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:
-
Start a Database Transaction: Use Laravel's
DB::transactionmethod to ensure atomicity. -
Check Inventory Quantities: Loop through the items you want to sell and check if each item's quantity is available in the inventory.
-
Save SoldInventoryItems: If all items have sufficient quantity, save them to the
SoldInventoryItemstable. -
Rollback if any condition fails: If any item does not have sufficient quantity, rollback the transaction.
Here's a code example to illustrate this:
use Illuminate\Support\Facades\DB;
use App\Models\Inventory;
use App\Models\SoldInventoryItem;
use App\Models\SoldInventoryInfo;
function saveSoldInventoryItems($soldInventoryInfoData, $soldInventoryItemsData)
{
DB::transaction(function () use ($soldInventoryInfoData, $soldInventoryItemsData) {
// Create SoldInventoryInfo record
$soldInventoryInfo = SoldInventoryInfo::create($soldInventoryInfoData);
foreach ($soldInventoryItemsData as $itemData) {
$inventory = Inventory::find($itemData['inventory_id']);
// Check if the inventory has enough quantity
if ($inventory->quantity < $itemData['quantity']) {
// If any item fails the check, throw an exception to rollback
throw new \Exception('Insufficient inventory for item ID: ' . $itemData['inventory_id']);
}
}
// If all checks pass, save the SoldInventoryItems
foreach ($soldInventoryItemsData as $itemData) {
SoldInventoryItem::create([
'sold_inventory_info_id' => $soldInventoryInfo->id,
'inventory_id' => $itemData['inventory_id'],
'quantity' => $itemData['quantity'],
]);
// Optionally, update the inventory quantity
$inventory = Inventory::find($itemData['inventory_id']);
$inventory->decrement('quantity', $itemData['quantity']);
}
});
}
Explanation:
-
Transaction: The
DB::transactionmethod 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
SoldInventoryItemand 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.