$model Morph to relation. */ class Answer extends Model { use HasFactory; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'answer', ]; /** * Perform any actions required after the model boots. * * @return void */ protected static function booted(): void { static::created(function (self $model) { self::resetCache($model); }); static::updated(function (self $model) { self::resetCache($model); }); static::deleted(function (self $model) { self::resetCache($model); }); } // * METHODS /** * Get all answers associated to the band. * * @param integer $questionModelKey * @return \Illuminate\Database\Eloquent\Collection */ public static function getAllModelsFromQuestion(int $questionModelKey): \Illuminate\Database\Eloquent\Collection { return self::getAnswers()->filter( fn($model) => $model->question->getKey() === $questionModelKey )->values(); } /** * Reset all cache elements related to this model. * * @param self $model * @return void */ private static function resetCache(self $model): void { $questionModelKey = $model->question->getKey(); Cache::forget("question-{$questionModelKey}-answers"); self::getAnswers(); } /** * Get all answers. * * @return \Illuminate\Database\Eloquent\Collection */ public static function getAnswers(): \Illuminate\Database\Eloquent\Collection { return Cache::remember('answers', 86400, function () { return self::query()->orderBy('answer', 'ASC')->get(); }); } // * RELATIONS /** * Question belongs to relation. * * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function question(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(Question::class); } /** * Customer morph to relation. * * @return \Illuminate\Database\Eloquent\Relations\MorphToMany */ public function customers(): \Illuminate\Database\Eloquent\Relations\MorphToMany { return $this->morphedByMany(Customer::class, 'model', 'model_answer', 'answer_id', 'model_id'); } /** * Customer morph to relation. * * @return \Illuminate\Database\Eloquent\Relations\MorphToMany */ public function singleOptins(): \Illuminate\Database\Eloquent\Relations\MorphToMany { return $this->morphedByMany(SingleOptin::class, 'model', 'model_answer', 'answer_id', 'model_id'); } }