Posts Learn Components Snippets Categories Tags Tools 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


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.
    <h1>{{ $this->post->title }}</h1>

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>

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


PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that are right for your project.

View Components

Sponsors 👑

+ Add Yours