morphTo(); } /** * Пользователь, который просмотрел */ public function user(): \Illuminate\Database\Eloquent\Relations\BelongsTo { return $this->belongsTo(User::class); } /** * Увеличить счетчик просмотров для модели */ public static function track(Viewable $viewable) { // Проверяем, не просматривал ли уже пользователь этот элемент //$existingView = static::forViewable($viewable)->first(); // if (!$existingView) { // return static::create([ // 'user_id' => null, // 'viewable_id' => $viewable->id, // 'viewable_type' => get_class($viewable), // ]); // } return static::create([ 'user_id' => null, 'viewable_id' => $viewable->id, 'viewable_type' => get_class($viewable), ]); //return $existingView; } /** * Scope для поиска просмотров определенной модели */ public function scopeForViewable($query, Viewable $viewable) { return $query->where('viewable_id', $viewable->id) ->where('viewable_type', get_class($viewable)) ->when(auth()->check(), function ($q) { $q->where('user_id', auth()->id()); }, function ($q) { $q->where('ip_address', request()->ip()); }); } /** * @return string[] */ public static function getStatus(): array { return [ self::DISABLE_STATUS => "Не активный", self::ACTIVE_STATUS => "Активный", ]; } }