MIF_E31221305/TA_API/app/Models/Wallet.php

67 lines
1.4 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Wallet extends Model
{
use HasFactory;
protected $fillable = [
'user_id',
'balance',
'status'
];
protected $casts = [
'id' => 'integer',
'user_id' => 'integer',
'balance' => 'float'
];
public function user()
{
return $this->belongsTo(User::class);
}
public function transactions()
{
return $this->hasMany(WalletTransaction::class);
}
public function withdrawals()
{
return $this->hasMany(Withdrawal::class);
}
public function addBalance($amount, $description, $booking = null)
{
$this->balance += $amount;
$this->save();
$this->transactions()->create([
'type' => 'credit',
'amount' => $amount,
'description' => $description,
'booking_id' => $booking ? $booking->id : null
]);
}
public function deductBalance($amount, $description)
{
if ($this->balance < $amount) {
throw new \Exception('Insufficient balance');
}
$this->balance -= $amount;
$this->save();
$this->transactions()->create([
'type' => 'debit',
'amount' => $amount,
'description' => $description
]);
}
}