I recently learned about caching in Laravel in a video series and wanted to apply it to my projects.
In this example project, I'm using a Livewire fullpage component (index) with 2 "modal" components each containing a "select" component which selects all records of a database table as a dropdown.
//Select Component Render Method
public function render()
{
$this->options = $this->modelName::orderBy($this->attribute, 'ASC')->get();
return view('components.input-field.select');
}
Select_Component_Controller_Example
My problem here is that this component is called in both the create modal and the edit modal. This causes a duplicate database query to be executed.
Double_Query_Executed_DebugBar
Unfortunately I am not quite clear how to apply the caching correctly now, in the example below you can see what I am trying to achieve. I would be very grateful for tips on the problem or even tutorial suggestions on the subject of caching, as I do not yet understand the application to this properly.
public function render()
{
$this->options = cache()->remember("options", 20, function() {
$this->modelName::orderBy($this->attribute, 'ASC')->get();
});
return view('components.input-field.select');
}
With kind regards, Daniel
CodePudding user response:
You must return the results in callback
$this->options = cache()->remember("options", 20, function() {
return $this->modelName::orderBy($this->attribute, 'ASC')->get();
});