90 lines
2.0 KiB
PHP
90 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Product extends Model
|
|
{
|
|
use HasFactory;
|
|
|
|
protected $fillable = [
|
|
'category_id',
|
|
'name',
|
|
'slug',
|
|
'sku',
|
|
'price',
|
|
'old_price',
|
|
'stock',
|
|
'short_description',
|
|
'description',
|
|
'image_path',
|
|
'gallery_paths',
|
|
'specs',
|
|
'is_active',
|
|
];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'price' => 'decimal:2',
|
|
'old_price' => 'decimal:2',
|
|
'stock' => 'integer',
|
|
'gallery_paths' => 'array',
|
|
'specs' => 'array',
|
|
'is_active' => 'boolean',
|
|
];
|
|
}
|
|
|
|
public function category()
|
|
{
|
|
return $this->belongsTo(Category::class);
|
|
}
|
|
|
|
public function getRouteKeyName(): string
|
|
{
|
|
return 'slug';
|
|
}
|
|
|
|
public function getImageUrlAttribute(): ?string
|
|
{
|
|
return $this->resolveImagePath($this->image_path);
|
|
}
|
|
|
|
public function getGalleryUrlsAttribute(): array
|
|
{
|
|
$paths = collect((array) ($this->gallery_paths ?? []))
|
|
->prepend($this->image_path)
|
|
->filter(fn ($path) => is_string($path) && trim($path) !== '')
|
|
->map(fn (string $path) => trim($path))
|
|
->unique()
|
|
->values();
|
|
|
|
return $paths
|
|
->map(fn (string $path) => $this->resolveImagePath($path))
|
|
->filter()
|
|
->values()
|
|
->all();
|
|
}
|
|
|
|
private function resolveImagePath(?string $path): ?string
|
|
{
|
|
$path = trim((string) $path);
|
|
if ($path === '') {
|
|
return null;
|
|
}
|
|
|
|
if (Str::startsWith($path, ['http://', 'https://', '/'])) {
|
|
return $path;
|
|
}
|
|
|
|
if (Str::startsWith($path, 'uploads/')) {
|
|
return asset($path);
|
|
}
|
|
|
|
return '/storage/' . ltrim($path, '/');
|
|
}
|
|
}
|