as a beginner I would like to ask your opinion about duplicate queries and how to avoid them?
I have the following example:
I have a model: Season with the following attributes: id, name, isCurrent.
In my app I need to show all Seasons so I have a function:
Duplicate because you use the getSeasons method to also fetch the Collection when you only need one record. Swap the code, so you can fetch the Collection first, then pick out the current season from that Collection, e.g.
public function mount()
{
$this->seasons = $this->getSeasons();
$this->currentSeason = $this->seasons->where('isCurrent', 1)->first();
}
public function getSeasons() {
return Season::get();
}
public function mount() {
$this->currentSeason = $this->getSeasons()->where('isCurrent', 1)->first();
$this->seasons = $this->getSeasons();
}
But that's awful.
Improvement No2
#[Computed]
public function seasons()
{
return Season::query()
->select([
'id',
'isCurrent',
... // Whatever else you need here
])
}
public function render()
{
return view('...', [
'currentSeason' => $this->seasons->where('isCurrent', true)->first()
]
}
Why is it better?
Easier for Livewire to parse non-primitive types (types that are not bool, int, string array). If you make the seasons or the current season a public property you would have the EloquentSynth (for the collection) and HydrateModel (for single model) to re-run queries to hydrate the models.
Seasons (collection) is retrieved once, and for the whole http roundtrip it is cached, without re-querying it again.
If your component is using the currentSeason, you can make it another computed property as currentSeason() and avoid HydrateModel procedure which re-queries the DB to retrieve the data for the model.
In case you don't know when EloquentSynth or HydrateModel happens, play around in your code and try making seasons a public collection and currentSeason a public Season properties.
Install debugbar and see in your queries that they will pop up.
I have almost turned every non-primitive properties into Computed and I have seen huge boost.