To achieve the desired functionality of cascading deletions and updating quantities, you can use Eloquent model events and transactions to ensure data integrity. Here's a step-by-step solution:
-
Delete the
SalesInvoice: When you delete aSalesInvoice, you should also delete the relatedSoldInventoryand itsSoldInventoryItems. -
Update
InventoryInStoreQuantities: Before deleting eachSoldInventoryItem, increment thequantityin the relatedInventoryInStore. -
Use Transactions: Wrap the operations in a database transaction to ensure that all operations succeed or fail together.
Here's how you can implement this:
use Illuminate\Support\Facades\DB;
class SalesInvoiceController extends Controller
{
public function deleteSalesInvoice($id)
{
DB::transaction(function () use ($id) {
// Find the SalesInvoice
$salesInvoice = SalesInvoice::findOrFail($id);
// Get the related SoldInventory
$soldInventory = $salesInvoice->soldInventory;
if ($soldInventory) {
// Get all SoldInventoryItems
$soldInventoryItems = $soldInventory->soldInventoryItems;
foreach ($soldInventoryItems as $item) {
// Find the related InventoryInStore
$inventoryInStore = $item->inventoryInStore;
if ($inventoryInStore) {
// Increment the InventoryInStore quantity
$inventoryInStore->increment('quantity', $item->quantity);
}
// Delete the SoldInventoryItem
$item->delete();
}
// Delete the SoldInventory
$soldInventory->delete();
}
// Finally, delete the SalesInvoice
$salesInvoice->delete();
});
}
}
Explanation:
-
Transaction: The
DB::transaction()method ensures that all database operations within the closure are executed as a single transaction. If any operation fails, the transaction is rolled back. -
Increment Quantity: Before deleting each
SoldInventoryItem, thequantityof the relatedInventoryInStoreis incremented by thequantityof theSoldInventoryItem. -
Cascading Deletions: After updating the quantities, the
SoldInventoryItemsare deleted, followed by theSoldInventory, and finally theSalesInvoice.
This approach ensures that your data remains consistent and that all related models are updated and deleted as required.