diff --git a/app/Livewire/Comment.php b/app/Livewire/Comment.php index cdda05c..bc632cf 100644 --- a/app/Livewire/Comment.php +++ b/app/Livewire/Comment.php @@ -1,10 +1,17 @@ '' ]; @@ -85,6 +96,34 @@ class Comment extends Component $this->dispatch('refresh')->self(); } + public function like() + { + if (! Auth::check()) { + return; + } + + Like::toggle($this->comment, User::where('id', Auth::user()->id)->firstOrFail()); + + Cache::forget('commentLikes'.$this->comment->id); + + if ($this->liked) { + $this->liked = false; + $this->likeCount--; + return; + } + + $this->liked = true; + $this->likeCount++; + } + + public function mount() + { + if (Auth::check()) { + $this->likeCount = $this->comment->likeCount(); + $this->liked = Like::has($this->comment, User::where('id', Auth::user()->id)->firstOrFail()); + } + } + public function render() { return view('livewire.comment'); diff --git a/app/Models/Comment.php b/app/Models/Comment.php index 45b4071..cc92d83 100644 --- a/app/Models/Comment.php +++ b/app/Models/Comment.php @@ -8,9 +8,16 @@ use Illuminate\Database\Eloquent\SoftDeletes; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Factories\HasFactory; +use Maize\Markable\Markable; +use Maize\Markable\Models\Like; + class Comment extends Model { - use HasFactory, SoftDeletes; + use HasFactory, SoftDeletes, Markable; + + protected static $marks = [ + Like::class + ]; /** * The attributes that are mass assignable. @@ -58,4 +65,12 @@ class Comment extends Model ? $this->parent->depth() + 1 : 0; } + + /** + * Get cached like count + */ + public function likeCount(): int + { + return cache()->remember('commentLikes' . $this->id, 300, fn() => $this->likes->count()); + } } diff --git a/resources/views/livewire/comment.blade.php b/resources/views/livewire/comment.blade.php index d136f2d..4128bbe 100644 --- a/resources/views/livewire/comment.blade.php +++ b/resources/views/livewire/comment.blade.php @@ -37,10 +37,28 @@
{!! $comment->presenter()->markdownBody() !!}
@endif -
+
+ @guest + + {{ $comment->likeCount() }} + + @endguest + + @auth + + + @endauth + {{ $comment->presenter()->relativeCreatedAt() }} + @auth @if ($comment->depth() < 2)