Ensure data integrity by cleaning up dependent records when deleting Sale or Expense models. This prevents orphaned transactions and ledgers in the database.
47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Database\Eloquent\Relations\MorphMany;
|
|
|
|
class Sale extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $guarded = [];
|
|
|
|
protected $casts = [
|
|
'happened_on' => 'date:Y-m-d',
|
|
];
|
|
|
|
/**
|
|
* Get all the transactions for the Sale
|
|
*/
|
|
public function transactions(): MorphMany
|
|
{
|
|
return $this->morphMany(Transaction::class, 'transactionable');
|
|
}
|
|
|
|
protected static function booted()
|
|
{
|
|
static::deleting(function ($sale) {
|
|
$sale->transactions->each(function ($transaction) {
|
|
// Delete associated ledgers first to trigger any ledger deletion logic if exists
|
|
$transaction->ledgers->each(function ($ledger) {
|
|
$ledger->balances()->delete(); // Delete balances associated with ledger
|
|
$ledger->delete();
|
|
});
|
|
$transaction->delete();
|
|
});
|
|
});
|
|
}
|
|
|
|
public function branch(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Branch::class);
|
|
}
|
|
}
|