Computed Properties in Laravel Livewire
An interesting feature in Livewire is the use of computed properties. These are simply functions defined in the component with the structure get<PropertyName>Property, and are consumed by simply accessing <PropertyName>. The main unique feature of these properties is that they are useful for deriving values from the database or other persistent storage, such as a cache.
app/Http/Livewire/Dashboard/Category/Index.php
public function getCategoryProperty()
{
if ($this->categoryToDelete)
return Category::find($this->categoryToDelete->id);
return "Sin categoría seleccionada";
}
To consume this property from the class or view, you must always use $this:
$this->category
You can display the value in the view as follows:
resources/views/livewire/dashboard/category/index.blade.php
"No category selected"
You can also declare a computed property using the #[Computed] attribute, as shown below:
// function getCategoryProperty()
#[Computed()]
function category() {
***
}
Let's implement a computed property that returns the current time and compare it with a traditional method to better understand its behavior:
#[Computed()]
function getTimeP()
{
sleep(1);
return time();
}
function getTime()
{
sleep(1);
return time();
}
Y en la vista:
{{ $this->getTimeP }}
{{ $this->getTimeP }}
{{ $this->getTimeP }}
{{ $this->getTimeP }}
{{ $this->getTimeP }}
<br>
{{$this->getTime()}}
{{$this->getTime()}}
When using computed properties, the value is automatically cached. Therefore, you'll see that no matter how many times it's called, getTimeP will return the same value, for example:
1728727286 1728727286 1728727286 1728727286 1728727286
In contrast, the traditional getTime() method will execute every time, so you'll get:
1728727287 1728727288
This demonstrates that computed properties cache the result until one of the internal properties that affect their result changes, or is explicitly updated.
Advantages of Computed Properties
Method with custom logic: You can build a property that internally performs complex operations, such as database queries or derived calculations.
Automatic caching: Once the value is calculated, it is saved internally. The method is not executed again unless a change in its dependencies is detected or it is explicitly updated.
This is ideal for expensive operations or when you want to avoid repeated calls to external services or the database.
class ShowUser extends Component
{
public $userId;
#[Computed]
public function user()
{
$key = 'user'.$this->getId();
$seconds = 3600; // 1 hour...
return Cache::remember($key, $seconds, function () {
return User::find($this->userId);
});
}
// ...
}
class ShowUser extends Component
{
public $userId;
#[Computed]
public function user()
{
return User::find($this->userId);
}
}
<h1>{{ $this->user->name }}</h1>
I agree to receive announcements of interest about this Blog.
Let's introduce computed properties in Laravel Livewire.
- Andrés Cruz