| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- <?php
-
- namespace App\Models;
-
- use App\Enums\ProductStatus;
- use Illuminate\Database\Eloquent\Attributes\Fillable;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Database\Eloquent\Relations\BelongsToMany;
- use Illuminate\Support\Str;
-
- /**
- * A group of products shoppers can browse, such as "Sun care" or "Gifts under RM 50".
- * Its page is /collections/{slug}; a "shop_by" section shows collections as tiles.
- *
- * @property int $id
- * @property int $store_id
- * @property string $name
- * @property string $slug
- * @property string|null $description
- * @property int $position
- * @property-read Store $store
- * @property-read \Illuminate\Database\Eloquent\Collection<int, Product> $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<Store, $this>
- */
- public function store(): BelongsTo
- {
- return $this->belongsTo(Store::class);
- }
-
- /**
- * @return BelongsToMany<Product, $this>
- */
- 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(),
- ];
- }
- }
|