-
Notifications
You must be signed in to change notification settings - Fork 0
Lazy computed properties
Here's an example of a computed property in a Livewire component:
class UpdatePosts extends Component
{
function getPostsProperty()
{
return Post::all();
}
function save()
{
$this->posts->each->save();
}
}In this case, $this->posts is the computed property generated by internally calling getPostsProperty() and using the returned value.
You might ask, what's the advantage of using computed properties instead of just calling a method like $this->posts() like so:
class UpdatePosts extends Component
{
function posts()
{
return Post::all();
}
function save()
{
$this->posts()->each->save();
}
}The main reason is, if you access $this->posts() twice in the same Livewire request, it will run two database queries. However, computed properties are cached for the duration of a request and if you retrieve $this->posts twice, the database will only be queried once.
Admittedly, this is in general a minor performance improvement.
Even without any performance implications, it feels nicer sometimes to access something like "posts" as a property rather than a method.