$products */ #[Fillable(['name', 'description', 'position'])] class Collection extends Model { protected static function booted(): void { static::creating(function (Collection $collection): void { $base = Str::slug($collection->name) ?: 'collection'; $slug = $base; $suffix = 2; while (static::query()->where('store_id', $collection->store_id)->where('slug', $slug)->exists()) { $slug = $base.'-'.$suffix++; } $collection->slug = $slug; }); } /** * @return BelongsTo */ public function store(): BelongsTo { return $this->belongsTo(Store::class); } /** * @return BelongsToMany */ public function products(): BelongsToMany { return $this->belongsToMany(Product::class)->withPivot('position')->orderByPivot('position'); } /** * What the storefront is allowed to see. The photo is the first active product's main photo. * * @return array{name: string, slug: string, description: string|null, image: string|null, count: int} */ public function toStorefront(): array { $active = $this->products->filter(fn (Product $product) => $product->status === ProductStatus::Active); $withPhoto = $active->first(fn (Product $product) => $product->images->isNotEmpty()); return [ 'name' => $this->name, 'slug' => $this->slug, 'description' => $this->description, 'image' => $withPhoto?->images->first()?->url(), 'count' => $active->count(), ]; } }