Skip to content

Lazy computed properties

Caleb Porzio edited this page Nov 1, 2022 · 4 revisions

Here's an example of a computed property in a Livewire component:

class UpdatePosts extends Component
{
    function getPostsProperty()
    {
        return Post::all();
    }

    function save()
    {
        $this->posts->each->save();
    }
}

In this case, $this->posts is the computed property generated by internally calling getPostsProperty() and using the returned value.

Why not just use methods?

You might ask, what's the advantage of using computed properties instead of just calling a method like $this->posts() like so:

class UpdatePosts extends Component
{
    function posts()
    {
        return Post::all();
    }

    function save()
    {
        $this->posts()->each->save();
    }
}

Reason A: Cacheing

The main reason is, if you access $this->posts() twice in the same Livewire request, it will run two database queries. However, computed properties are cached for the duration of a request and if you retrieve $this->posts twice, the database will only be queried once.

Admittedly, this is in general a minor performance improvement.

Reason B: Aesthetics

Even without any performance implications, it feels nicer sometimes to access something like "posts" as a property rather than a method.

Clone this wiki locally