$images */ #[Fillable(['name', 'description', 'price', 'compare_at_price', 'stock', 'status'])] class Product extends Model { /** @use HasFactory */ use HasFactory; protected static function booted(): void { static::creating(function (Product $product): void { $product->slug = $product->uniqueSlug($product->name); }); // The database removes the image rows by itself. The files need removing here. static::deleting(function (Product $product): void { $product->images->each->delete(); }); } /** * A web-address name made from the product name, unique within its store. */ private function uniqueSlug(string $name): string { $base = Str::slug($name) ?: 'product'; $slug = $base; $suffix = 2; while (static::query()->where('store_id', $this->store_id)->where('slug', $slug)->exists()) { $slug = $base.'-'.$suffix++; } return $slug; } /** * @return BelongsTo */ public function store(): BelongsTo { return $this->belongsTo(Store::class); } /** * @return HasMany */ public function images(): HasMany { return $this->hasMany(ProductImage::class)->orderBy('position')->orderBy('id'); } /** * Products shoppers may see. * * @param Builder $query */ public function scopeActive(Builder $query): void { $query->where('status', ProductStatus::Active); } /** * What the storefront is allowed to see. Prices are in ringgit here. * * @return array */ public function toStorefront(): array { $images = $this->images->map(fn (ProductImage $image) => $image->url())->all(); return [ 'id' => $this->id, 'name' => $this->name, 'slug' => $this->slug, 'description' => $this->description, 'price' => $this->price / 100, 'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null, 'in_stock' => $this->stock > 0, 'stock_left' => $this->stock, 'image' => $images[0] ?? null, 'images' => $images, ]; } /** * @return array */ protected function casts(): array { return [ 'status' => ProductStatus::class, 'price' => 'integer', 'compare_at_price' => 'integer', 'stock' => 'integer', ]; } }