Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Livewire

Building a Like Button with Livewire v4

Create an optimistic like button.

1 February 20261 min readLivewireاقرأ بالعربية

On this page

  1. Component

Build a like button with optimistic UI.

Component

php
@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
All articles

Keep reading

  • Authorization in Livewire v4 Components1 February 20261 min read
  • Blaze Pre-Compiler: Massive Performance Gains in Livewire v41 February 20261 min read
  • Building a Bookmark Feature with Livewire v41 February 20261 min read