AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Collection.php 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Models;
  3. use App\Enums\ProductStatus;
  4. use Illuminate\Database\Eloquent\Attributes\Fillable;
  5. use Illuminate\Database\Eloquent\Model;
  6. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  7. use Illuminate\Database\Eloquent\Relations\BelongsToMany;
  8. use Illuminate\Support\Str;
  9. /**
  10. * A group of products shoppers can browse, such as "Sun care" or "Gifts under RM 50".
  11. * Its page is /collections/{slug}; a "shop_by" section shows collections as tiles.
  12. *
  13. * @property int $id
  14. * @property int $store_id
  15. * @property string $name
  16. * @property string $slug
  17. * @property string|null $description
  18. * @property int $position
  19. * @property-read Store $store
  20. * @property-read \Illuminate\Database\Eloquent\Collection<int, Product> $products
  21. */
  22. #[Fillable(['name', 'description', 'position'])]
  23. class Collection extends Model
  24. {
  25. protected static function booted(): void
  26. {
  27. static::creating(function (Collection $collection): void {
  28. $base = Str::slug($collection->name) ?: 'collection';
  29. $slug = $base;
  30. $suffix = 2;
  31. while (static::query()->where('store_id', $collection->store_id)->where('slug', $slug)->exists()) {
  32. $slug = $base.'-'.$suffix++;
  33. }
  34. $collection->slug = $slug;
  35. });
  36. }
  37. /**
  38. * @return BelongsTo<Store, $this>
  39. */
  40. public function store(): BelongsTo
  41. {
  42. return $this->belongsTo(Store::class);
  43. }
  44. /**
  45. * @return BelongsToMany<Product, $this>
  46. */
  47. public function products(): BelongsToMany
  48. {
  49. return $this->belongsToMany(Product::class)->withPivot('position')->orderByPivot('position');
  50. }
  51. /**
  52. * What the storefront is allowed to see. The photo is the first active product's main photo.
  53. *
  54. * @return array{name: string, slug: string, description: string|null, image: string|null, count: int}
  55. */
  56. public function toStorefront(): array
  57. {
  58. $active = $this->products->filter(fn (Product $product) => $product->status === ProductStatus::Active);
  59. $withPhoto = $active->first(fn (Product $product) => $product->images->isNotEmpty());
  60. return [
  61. 'name' => $this->name,
  62. 'slug' => $this->slug,
  63. 'description' => $this->description,
  64. 'image' => $withPhoto?->images->first()?->url(),
  65. 'count' => $active->count(),
  66. ];
  67. }
  68. }