<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Product extends Model
{
protected $fillable = [
'category_id', 'name', 'slug', 'sku', 'short_description', 'description',
'regular_price', 'sale_price', 'offer_text',
'shipping_inside_dhaka', 'shipping_outside_dhaka',
'stock', 'status', 'featured', 'thumbnail', 'sort_order',
];
protected $casts = [
'regular_price' => 'decimal:2',
'sale_price' => 'decimal:2',
'status' => 'boolean',
'featured' => 'boolean',
];
protected static function boot()
{
parent::boot();
static::creating(function ($product) {
if (empty($product->slug)) {
$product->slug = Str::slug($product->name);
}
if (empty($product->sku)) {
$product->sku = 'SKU-' . strtoupper(Str::random(8));
}
});
}
public function category()
{
return $this->belongsTo(Category::class);
}
public function images()
{
return $this->hasMany(ProductImage::class)->orderBy('sort_order');
}
public function variations()
{
return $this->hasMany(ProductVariation::class);
}
public function tags()
{
return $this->belongsToMany(Tag::class, 'product_tag');
}
public function getThumbnailUrlAttribute()
{
return $this->thumbnail
? asset('storage/' . $this->thumbnail)
: asset('images/no-product.svg');
}
public function getCurrentPriceAttribute()
{
return $this->sale_price ?? $this->regular_price;
}
public function getIsOnSaleAttribute()
{
return $this->sale_price && $this->sale_price < $this->regular_price;
}
public function scopeActive($query)
{
return $query->where('status', true);
}
public function scopeFeatured($query)
{
return $query->where('featured', true);
}
}