showing likes with livewire

This commit is contained in:
Ghostie 2024-08-23 20:15:18 -05:00
parent 25d3af87e8
commit 537f354abb
3 changed files with 39 additions and 36 deletions

View File

@ -6,6 +6,31 @@ use Livewire\Component;
class LikePost extends Component
{
public $post;
public $isLiked;
public $likes;
public function mount($post)
{
$this->isLiked = $post->checkLike(auth()->user());
$this->likes = $post->likes->count();
}
public function like()
{
if ($this->post->checkLike(auth()->user())) {
$this->post->likes()->where("post_id", $this->post->id)->delete();
$this->isLiked = false;
$this->likes--;
} else {
$this->post->likes()->create([
"user_id" => auth()->user()->id
]);
$this->isLiked = true;
$this->likes++;
}
}
public function render()
{
return view('livewire.like-post');

View File

@ -1,3 +1,15 @@
<div>
<h1>Hello, World!</h1>
<div class="flex gap-2 items-center">
<button wire:click="like">
<svg xmlns="http://www.w3.org/2000/svg" fill="{{ $isLiked ? 'red' : 'white' }}" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="size-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z" />
</svg>
</button>
<p class="font-bold">{{ $likes }}
<span class="font-normal">Likes</span>
</p>
</div>
</div>

View File

@ -11,42 +11,8 @@
<div class="p-3 flex items-center gap-4">
@auth
<livewire:like-post />
@if ($post->checkLike(auth()->user()))
<form method="POST" action="{{ route('posts.likes.destroy', $post) }}">
@csrf
@method('DELETE')
<div class="my-4">
<button type="submit">
<svg xmlns="http://www.w3.org/2000/svg" fill="red" viewBox="0 0 24 24" stroke-width="1.5"
stroke="currentColor" class="size-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z" />
</svg>
</button>
</div>
</form>
@else
<form method="POST" action="{{ route('posts.likes.store', $post) }}">
@csrf
<div class="my-4">
<button type="submit">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"
stroke-width="1.5" stroke="currentColor" class="size-6">
<path stroke-linecap="round" stroke-linejoin="round"
d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12Z" />
</svg>
</button>
</div>
</form>
@endif
<livewire:like-post :post="$post" />
@endauth
<p class="font-bold">{{ $post->likes->count() }}
<span class="font-normal">Likes</span>
</p>
</div>
<div>