AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ProductVariant.php 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Model;
  4. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  5. use Illuminate\Database\Eloquent\Relations\HasMany;
  6. /**
  7. * One combination of a product's options, such as "500g / Pedas", with its own price and stock.
  8. * Prices are in sen (1 ringgit = 100 sen).
  9. *
  10. * @property int $id
  11. * @property int $store_id
  12. * @property int $product_id
  13. * @property string $option1
  14. * @property string|null $option2
  15. * @property int $price
  16. * @property int|null $compare_at_price
  17. * @property int $stock
  18. * @property int $position
  19. * @property-read Product $product
  20. */
  21. class ProductVariant extends Model
  22. {
  23. /**
  24. * @return BelongsTo<Product, $this>
  25. */
  26. public function product(): BelongsTo
  27. {
  28. return $this->belongsTo(Product::class);
  29. }
  30. /**
  31. * The bundles this variant is inside.
  32. *
  33. * @return HasMany<BundleItem, $this>
  34. */
  35. public function usedInBundles(): HasMany
  36. {
  37. return $this->hasMany(BundleItem::class, 'variant_id');
  38. }
  39. /**
  40. * The option values in order, without empty ones.
  41. *
  42. * @return list<string>
  43. */
  44. public function values(): array
  45. {
  46. return array_values(array_filter([$this->option1, $this->option2], fn (?string $value) => $value !== null && $value !== ''));
  47. }
  48. /**
  49. * "500g / Pedas".
  50. */
  51. public function name(): string
  52. {
  53. return implode(' / ', $this->values());
  54. }
  55. /**
  56. * What the storefront is allowed to see. Prices are in ringgit here.
  57. *
  58. * @return array<string, mixed>
  59. */
  60. public function toStorefront(): array
  61. {
  62. return [
  63. 'id' => $this->id,
  64. 'name' => $this->name(),
  65. 'options' => $this->values(),
  66. 'price' => $this->price / 100,
  67. 'compare_at_price' => $this->compare_at_price !== null ? $this->compare_at_price / 100 : null,
  68. 'in_stock' => $this->stock > 0,
  69. 'stock_left' => $this->stock,
  70. ];
  71. }
  72. /**
  73. * @return array<string, string>
  74. */
  75. protected function casts(): array
  76. {
  77. return [
  78. 'price' => 'integer',
  79. 'compare_at_price' => 'integer',
  80. 'stock' => 'integer',
  81. 'position' => 'integer',
  82. ];
  83. }
  84. }