morphMany(Like::class, 'likeable'); } public function getIsLikedAttribute() { if (!auth()->check()) return false; return $this->likes() ->where('user_id', auth()->id()) ->exists(); } public function getLikesCountAttribute() { return $this->likes()->count(); } public function toggleLike() { if ($this->getIsLikedAttribute()) { return $this->removeLike(); } else { return $this->addLike(); } } public function addLike() { if ($this->getIsLikedAttribute()) return false; return Like::create([ 'user_id' => auth()->id(), 'likeable_id' => $this->id, 'likeable_type' => get_class($this), ]); } public function removeLike() { if (!$this->getIsLikedAttribute()) return false; return Like::where([ 'user_id' => auth()->id(), 'likeable_id' => $this->id, 'likeable_type' => get_class($this), ])->delete(); } }