Add likes to comments

This commit is contained in:
2026-01-10 19:41:23 +01:00
parent 41c34e6d89
commit b133db0573
3 changed files with 74 additions and 2 deletions

View File

@@ -1,10 +1,17 @@
<?php
namespace App\Livewire;
use App\Models\User;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Maize\Markable\Models\Like;
class Comment extends Component
{
use AuthorizesRequests;
@@ -13,6 +20,10 @@ class Comment extends Component
public $isReplying = false;
public $likeCount = 0;
public $liked = false;
public $replyState = [
'body' => ''
];
@@ -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');

View File

@@ -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());
}
}