Posts Learn Snippets Categories Tags About
/

How to Define Computed Properties in Laravel Livewire

Learn how to define computed properties in Laravel Livewire to dynamically access the value that have been set on the go

Created on Jul 06, 2021

14 views

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

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.