Building a Like Button with Livewire v4
February 01, 2026
•
1 min read
•
9 views
Build a like button with optimistic UI.
Component
@php
new class extends Livewire\Component {
public Post $post;
public bool $liked = false;
public int $count = 0;
public function mount(Post $post): void
{
$this->post = $post;
$this->liked = $post->isLikedBy(auth()->user());
$this->count = $post->likes_count;
}
public function toggle(): void
{
if ($this->liked) {
$this->post->unlike(auth()->user());
$this->count--;
} else {
$this->post->like(auth()->user());
$this->count++;
}
$this->liked = !$this->liked;
}
}
@endphp
Related Posts
Introduction to Livewire v4: The Future of Laravel Full-Stack Development
Discover what's new in Livewire v4 and why it's a game-changer for Laravel developers.
Single-File Components in Livewire v4: The View-First Approach
Learn how to create single-file components with the new .wire.php extension.
Multi-File Components (MFC) in Livewire v4
Organize complex components with the new multi-file component structure.
Comments (0)
No comments yet. Be the first to comment!