90 lines
2.1 KiB
PHP
90 lines
2.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Attributes\Scope;
|
|
use Illuminate\Database\Eloquent\Builder;
|
|
use Illuminate\Database\Eloquent\Casts\Attribute;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Spatie\MediaLibrary\HasMedia;
|
|
use Spatie\MediaLibrary\InteractsWithMedia;
|
|
use Spatie\Sluggable\HasSlug;
|
|
use Spatie\Sluggable\SlugOptions;
|
|
|
|
class Product extends Model implements HasMedia
|
|
{
|
|
use HasFactory, HasSlug, InteractsWithMedia, SoftDeletes;
|
|
|
|
protected $guarded = ['id'];
|
|
|
|
protected $appends = [
|
|
'thumbnail_url',
|
|
'images_data',
|
|
];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'is_active' => 'boolean',
|
|
];
|
|
}
|
|
|
|
#[Scope]
|
|
protected function active(Builder $query): void
|
|
{
|
|
$query->where('is_active', true);
|
|
}
|
|
|
|
#[Scope]
|
|
protected function inactive(Builder $query): void
|
|
{
|
|
$query->where('is_active', false);
|
|
}
|
|
|
|
public function getSlugOptions(): SlugOptions
|
|
{
|
|
return SlugOptions::create()
|
|
->generateSlugsFrom('name')
|
|
->saveSlugsTo('slug');
|
|
}
|
|
|
|
public function registerMediaCollections(): void
|
|
{
|
|
$this->addMediaCollection('thumbnail')
|
|
->singleFile();
|
|
|
|
$this->addMediaCollection('images');
|
|
}
|
|
|
|
protected function thumbnailUrl(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => $this->getFirstMediaUrl('thumbnail') ?: null,
|
|
);
|
|
}
|
|
|
|
protected function imagesData(): Attribute
|
|
{
|
|
return Attribute::make(
|
|
get: fn () => $this->getMedia('images')->map(fn ($media) => [
|
|
'id' => $media->id,
|
|
'url' => $media->getUrl(),
|
|
])->toArray(),
|
|
);
|
|
}
|
|
|
|
public function prices(): HasMany
|
|
{
|
|
return $this->hasMany(ProductPrice::class);
|
|
}
|
|
|
|
public function categories(): BelongsToMany
|
|
{
|
|
return $this->belongsToMany(Category::class);
|
|
}
|
|
}
|