Home / Snippets / How to Define Computed Properties in Laravel Livewire
How to Define Computed Properties in Laravel Livewire cover

How to Define Computed Properties in Laravel Livewire

1.6K

3 years ago

0 comments

Computed properties are dynamic properties that can be used to access derived properties from the database. What that means is that the method can execute some logic beforehand then right away accessible just like how class properties are normally accessed.

If you have "getPostProperty" method then it can be accessed through the "$this->post" variable. Otherwise, if you have "getUserProperty" method then it's accessible through the "$this->user" variable.

class ShowPost extends Component
{
    // Computed Property
    public function getPostProperty()
    {
        return Post::find($this->postId);
    }
}

In the blade views to access the computed property "$this" must be used before the property name. In this case "$this->post" is an object so the "title" property can also be accessed from the object.
<div>
    <h1>{{ $this->post->title }}</h1>
</div>

If the computed property returned an array then you can loop it from the blade template.
@foreach($this->posts as $post)
    <h1>{{ $post->title }}</h1>
@endforeach
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this