In this episode, we dive deeper into computed properties in Laravel Livewire, building on what we discussed previously. We start by creating a new Livewire component for confirming the deletion of an employee. Instead of passing the entire employee object, we pass just the employee's ID to the component, then use that ID to look up the employee in the database. This sets us up nicely for the main topic: cached computed properties.
First, we take the straightforward approach—querying the database both when rendering the component and when handling the deletion action. We quickly spot the inefficiency: each render and each action trigger a new database query, which adds up, especially in components where you'll need to reference the same model multiple times.
To solve this, we refactor to use a computed property. We implement the getEmployeeProperty
method in the Livewire component and show how it automatically caches the retrieved employee model for the entire lifetime of the current request. Now, we can reference this->employee
anywhere in our component or view, and Livewire ensures it only does a single database query, no matter how many times we access it.
We wrap up by showing you how to use this computed property directly in your Blade views, and how it pays off by keeping your code cleaner and your database queries minimal. The big takeaway: use computed (and cached) properties to reduce duplicate queries and keep your Livewire components efficient!