*/ protected $fillable = [ 'question', 'type', 'brand_id', ]; /** * Map attribute names to enum classes. * * @var array */ protected $casts = [ 'type' => QuestionType::class, ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::created(function (self $model) { self::resetCache($model->getKey()); }); static::updated(function (self $model) { self::resetCache($model->getKey()); }); static::deleted(function (self $model) { self::resetCache($model->getKey()); }); } // * METHODS /** * Get all questions associated to the band. * * @param integer $brandModelKey * @return \Illuminate\Database\Eloquent\Collection */ public static function getAllModelsFromBrand(int $brandModelKey): \Illuminate\Database\Eloquent\Collection { return self::getQuestions()->filter( fn($model) => $model->brand->getKey() === $brandModelKey )->values(); } /** * Reset all cache elements related to this model. * * @param integer $modelKey * @return void */ private static function resetCache(int $modelKey): void { Cache::forget('questions'); Cache::forget("question-{$modelKey}-answers"); self::getQuestions(); } /** * Get all questions. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getQuestions(): \Illuminate\Database\Eloquent\Collection { return Cache::remember('questions', 86400, function () { return self::query()->orderBy('question', 'ASC')->get(); }); } // * RELATIONS /** * Brand belongs to relation. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function brand(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Brand::class); } /** * Answer has many relation. * * @return \Illuminate\Database\Eloquent\Relations\HasMany */ public function answers(): \Illuminate\Database\Eloquent\Relations\HasMany { return $this->hasMany(Answer::class); } }