store/app/Models/RestockItem.php

81 lines
1.9 KiB
PHP

<?php
namespace App\Models;
use App\Models\Concerns\InteractsWithActivityLog;
use Illuminate\Database\Eloquent\Attributes\Appends;
use Illuminate\Database\Eloquent\Attributes\Guarded;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;
#[Guarded(['id'])]
#[Appends([
'quantity_formatted',
'quantity_input',
'subtotal_formatted',
'unit_price_formatted',
])]
class RestockItem extends Model
{
// 1. Use Trait
use HasFactory, InteractsWithActivityLog, SoftDeletes;
// 2. Casting
protected function casts(): array
{
return [
'quantity' => 'integer',
'subtotal' => 'integer',
'unit_price' => 'integer',
];
}
// 3. Attribute
public function quantityFormatted(): Attribute
{
return Attribute::make(
get: fn () => "{$this->quantity} pcs",
);
}
public function quantityInput(): Attribute
{
return Attribute::make(
get: fn () => (string) $this->quantity,
);
}
public function subtotalFormatted(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->subtotal, 0, ',', '.'),
);
}
public function unitPriceFormatted(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->unit_price, 0, ',', '.'),
);
}
// 4. Relation
public function restock(): BelongsTo
{
return $this->belongsTo(Restock::class)->withTrashed();
}
public function productVariant(): BelongsTo
{
return $this->belongsTo(ProductVariant::class)->withTrashed();
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class)->withTrashed();
}
}