#[Computed]
Create cached, derived values from your component state.
Basic Usage
Computed properties are methods that calculate a value and cache it for the request.
use LiVue\Attributes\Computed;
class Cart extends Component
{
public array $items = [];
#[Computed]
public function total(): float
{
return collect($this->items)
->sum(fn($item) => $item['price'] * $item['quantity']);
}
#[Computed]
public function itemCount(): int
{
return count($this->items);
}
}
Using in Templates
Access computed properties using the $this->propertyName magic getter or directly in Blade.
<div>
<p>Items in cart: {{ $this->itemCount }}</p>
<p>Total: ${{ number_format($this->total, 2) }}</p>
</div>
Caching Behavior
Computed values are cached for the duration of a single request. Multiple accesses don't re-execute the method.
#[Computed]
public function expensiveCalculation(): array
{
// This only runs once per request,
// even if accessed multiple times in the template
return DB::table('analytics')
->where('user_id', $this->userId)
->get();
}
Clearing the Cache
If you need to recalculate a computed value within the same request, you can clear the cache.
public function addItem($item)
{
$this->items[] = $item;
// Force recalculation of computed properties
unset($this->total);
}
When to Use
Good Use Cases
- • Derived values (totals, counts, averages)
- • Expensive calculations
- • Formatted data for display
- • Filtered/sorted collections
Avoid For
- • Values that need to be editable
- • Data that changes within a request
- • Simple property access