ctrlpanel/app/Models/Voucher.php

79 lines
1.5 KiB
PHP
Raw Normal View History

2021-07-09 22:18:22 +00:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
* Class Voucher
* @package App\Models
*/
class Voucher extends Model
{
use HasFactory;
/**
* @var string[]
*/
protected $fillable = [
'memo',
'code',
'credits',
'uses',
'expires_at',
];
protected $dates = [
'expires_at'
];
/**
*
*/
public static function boot()
{
parent::boot();
static::deleting(function (Voucher $voucher) {
$voucher->users()->detach();
});
}
2021-07-10 06:58:11 +00:00
/**
* @return string
*/
2021-07-09 22:18:22 +00:00
public function getStatus(){
if ($this->users()->count() >= $this->uses) return 'USES_LIMIT_REACHED';
2021-07-10 06:58:11 +00:00
if (!is_null($this->expires_at)){
if ($this->expires_at->isPast()) return 'EXPIRED';
}
2021-07-09 22:18:22 +00:00
return 'VALID';
}
/**
2021-07-10 06:58:11 +00:00
* @param User $user
* @return float
*/
public function redeem(User $user){
try {
$user->increment('credits' , $this->credits);
$this->users()->attach($user);
}catch (\Exception $exception) {
throw $exception;
}
return $this->credits;
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
2021-07-09 22:18:22 +00:00
*/
public function users()
{
return $this->belongsToMany(User::class);
}
}