*/ protected $fillable = [ 'title', 'video_id', 'product_id', 'is_on_homepage', 'order', 'published', ]; /** * The attributes that should be cast. * * @var array */ protected $casts = [ 'published' => 'boolean', 'is_on_homepage' => 'boolean', ]; /** * Perform any actions required after the model boots. */ protected static function booted(): void { static::creating(function (self $video) { self::setOrder($video); }); static::created(function () { self::resetCache(); }); static::updated(function () { self::resetCache(); }); static::deleted(function () { self::resetCache(); }); } // * METHODS /** * Set order after the last element of the list. */ private static function setOrder(self $model): void { $model->order = \intval(self::query()->max('order')) + 1; } /** * Reset all cache elements related to this model. */ private static function resetCache(): void { Cache::forget('9publishedHomeVideosOrderedByOrderWithProducts'); self::get9PublishedHomeVideosOrderedWithProducts(); Cache::forget('6publishedVideosOrderedByOrderWithProducts'); self::get6PublishedVideosOrderedWithProducts(); } /** * Get 9 published Videos to display in homepage ordered by order with products relations. */ public static function get9PublishedHomeVideosOrderedWithProducts(): Collection { return Cache::remember('9publishedHomeVideosOrderedByOrderWithProducts', 86400, function () { return self::query() ->where('published', true) ->where('is_on_homepage', true) ->orderBy('order') ->with('product') ->limit(9) ->get(); }); } /** * Get 9 published Videos to display in homepage ordered by order with products relations. */ public static function get6PublishedVideosOrderedWithProducts(): Collection { return Cache::remember('6publishedVideosOrderedByOrderWithProducts', 86400, function () { return self::query() ->where('published', true) ->orderBy('order') ->with('product') ->take(6) ->get(); }); } /** * Create a SchemaOrg. */ public function toSchemaOrg(): MediaObject { $url = (IsValidVimeoId::validates($this->video_id)) ? "https://player.vimeo.com/video/$this->video_id" : "https://www.youtube.com/embed/$this->video_id"; return Schema::mediaObject() ->name($this->title) ->productionCompany($this->getOrganizationSchema()) ->embedUrl($url); } // * RELATIONSHIPS /** * Get the product for the video. */ public function product(): BelongsTo { return $this->belongsTo(Product::class); } }