Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PetroGromovo's avatar

in which cases using of computes in livewire gives some advantages ?

reading docs at https://livewire.laravel.com/docs/computed-properties#when-to-use-computed-properties I wonder in which cases using of computes gives some advantages ? Please, give several examples !

Thanks in advance!

0 likes
1 reply
kevinbui's avatar
kevinbui
Best Answer
Level 41

All the examples in your shared link are spot on.

I recall there's a different example in this talk.

Besides the use in your shared link, just like computed properties in Vue.js, I simply use computed properties in Livewire to write cleaner code getting info deriving from existing data.

Considering the below example:

public class PostFormModal extends Component
{
    public Post $post;

    public function boot()
    {
        $this->post = new Post();
    }

    public funtion setPost(Post $post): void
    {
        $this->post = $post;
    }

    #[Computed]
    public function modalTitle(): string
    {
        if ($this->post->exists) {
            return "Edit post #{$this->post->id}";
        }

        return "Create A New Post";
    }
}

So the modal title will change depending on the binding post, or the current functionality.

A different example could be:

use Illuminate\Database\Eloquent\Collection;

public class PostList extends Component
{
    public Collection $posts;

    public function boot()
    {
        $this->posts = Post::all();
    }

    #[Computed]
    public function numberOfPosts(): int
    {
        return $this->posts->count();
    }

    #[Computed]
    public function archived(): int
    {
        return $this->posts->filter->archived;
    }
}
1 like

Please or to participate in this conversation.