| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- <?php
-
- namespace App\Models;
-
- use App\Enums\StoreCategory;
- use App\Enums\StoreLanguage;
- use App\Enums\StoreStatus;
- use Database\Factories\StoreFactory;
- use Illuminate\Database\Eloquent\Attributes\Fillable;
- use Illuminate\Database\Eloquent\Factories\HasFactory;
- use Illuminate\Database\Eloquent\Model;
- use Illuminate\Database\Eloquent\Relations\BelongsTo;
- use Illuminate\Support\Carbon;
- use Illuminate\Support\Str;
-
- /**
- * A merchant's online store. Every store-related table points back here with `store_id`.
- *
- * @property int $id
- * @property int $user_id
- * @property string $name
- * @property string $slug
- * @property StoreCategory $category
- * @property string $description
- * @property StoreLanguage $language
- * @property StoreStatus $status
- * @property array<string, mixed>|null $plan
- * @property Carbon|null $created_at
- * @property Carbon|null $updated_at
- */
- #[Fillable(['name', 'category', 'description', 'language'])]
- class Store extends Model
- {
- /** @use HasFactory<StoreFactory> */
- use HasFactory;
-
- /**
- * Slugs that can never be used, because they will clash with our own subdomains.
- *
- * @var list<string>
- */
- public const array RESERVED_SLUGS = ['www', 'app', 'api', 'admin', 'dashboard', 'mail', 'store', 'stores', 'create'];
-
- /**
- * Default values for new stores.
- *
- * @var array<string, string>
- */
- protected $attributes = [
- 'language' => 'en',
- 'status' => 'draft',
- ];
-
- protected static function booted(): void
- {
- static::creating(function (Store $store) {
- if (blank($store->slug)) {
- $store->slug = static::uniqueSlug($store->name);
- }
- });
- }
-
- /**
- * Build a web-safe slug from a store name that no other store is using.
- */
- public static function uniqueSlug(string $name): string
- {
- $base = Str::slug($name) ?: 'store';
- $slug = $base;
- $suffix = 2;
-
- while (in_array($slug, self::RESERVED_SLUGS, true) || static::query()->where('slug', $slug)->exists()) {
- $slug = $base.'-'.$suffix++;
- }
-
- return $slug;
- }
-
- public function getRouteKeyName(): string
- {
- return 'slug';
- }
-
- /**
- * @return BelongsTo<User, $this>
- */
- public function user(): BelongsTo
- {
- return $this->belongsTo(User::class);
- }
-
- /**
- * Get the attributes that should be cast.
- *
- * @return array<string, string>
- */
- protected function casts(): array
- {
- return [
- 'category' => StoreCategory::class,
- 'language' => StoreLanguage::class,
- 'status' => StoreStatus::class,
- 'plan' => 'array',
- ];
- }
- }
|