*/ use BelongsToTenant, HasFactory, InteractsWithMedia; public const COLLECTION = 'image'; /** Generated widths in px, used for srcset. */ public const WIDTHS = ['sm' => 640, 'md' => 1280, 'lg' => 2048]; /** * Get the attributes that should be cast. * * @return array */ protected function casts(): array { return [ 'category' => PhotoCategory::class, 'is_published' => 'boolean', ]; } public function registerMediaCollections(): void { // Website photos are public files; the app's default disk (FILESYSTEM_DISK=local) is private. $this->addMediaCollection(self::COLLECTION) ->useDisk('public') ->singleFile() ->acceptsMimeTypes(['image/jpeg', 'image/png', 'image/webp']); } public function registerMediaConversions(?Media $media = null): void { foreach (self::WIDTHS as $name => $width) { $this->addMediaConversion($name) ->fit(Fit::Max, $width, $width) ->format('webp') ->quality(80) ->performOnCollections(self::COLLECTION); } } /** * @return BelongsTo */ public function property(): BelongsTo { return $this->belongsTo(Property::class); } /** * @param Builder $query * @return Builder */ #[Scope] protected function published(Builder $query): Builder { return $query->where('is_published', true)->orderBy('sort_order'); } /** * Photos a gallery or an automatic choice may show – floor plans and drawings only appear where chosen. * * @param Builder $query * @return Builder */ #[Scope] protected function forGalleries(Builder $query): Builder { return $query->whereIn('category', PhotoCategory::forGalleries()); } /** * Photos of the apartment and those without an apartment (e.g. the area); without an apartment all photos. * * @param Builder $query * @return Builder */ #[Scope] protected function forProperty(Builder $query, ?Property $property): Builder { return $property === null ? $query : $query->where(fn (Builder $query) => $query->where('property_id', $property->id)->orWhereNull('property_id')); } public function url(string $size = 'md'): string { return $this->getFirstMediaUrl(self::COLLECTION, $size); } /** * srcset for , e.g. "…-sm.webp 640w, …-md.webp 1280w, …-lg.webp 2048w". */ public function srcset(): string { return collect(self::WIDTHS) ->map(fn (int $width, string $name): string => $this->url($name).' '.$width.'w') ->implode(', '); } }