store/app/Models/ProductPrice.php

50 lines
1.2 KiB
PHP

<?php
namespace App\Models;
use App\Enums\PriceType;
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;
#[Guarded(['id'])]
#[Appends(['price_formatted', 'price_input'])]
class ProductPrice extends Model
{
// 1. Use Trait
use HasFactory;
// 2. Casting
protected function casts(): array
{
return [
'price' => 'integer',
'type' => PriceType::class,
];
}
// 3. Attribute
public function priceFormatted(): Attribute
{
return Attribute::make(
get: fn () => 'Rp '.number_format($this->price, 0, ',', '.'),
);
}
public function priceInput(): Attribute
{
return Attribute::make(
get: fn () => (string) $this->price,
);
}
// 4. Relation
public function variant(): BelongsTo
{
return $this->belongsTo(ProductVariant::class, 'variant_id')->withTrashed();
}
}