This commit is contained in:
89
app/Models/Product.php
Normal file
89
app/Models/Product.php
Normal file
@@ -0,0 +1,89 @@
|
||||
<?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, '/');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user