So my 1st question is: Should I create a model for something like this? I'm worried because I have no idea how the model works underneath the covers, and I don't want it needlessly reading from the table or prepping it to be written to or something else.
All you want to do is to abstract that query via some function and invoke on demand ensuring that query could run only once. It actually just an approach and has nothing to do with a framework.
The workflow would look like this,
- A function/class method that fetch records should be prepared
- When accessing fetched records, you have to ensure if they haven't been accessed before - call that function only once, and save its returned value. Next time on accessing check if that value is not null.
- And finally render that
My next question: Barring your answer of my 1st question, could you please provide a basic example of how I'd accomplish this.
function fetchStates() {
static $result = null;
// If this function has never been called before, then invoke a query
if ($result === null) {
$result = DB::select('select distinct state_alpha,state_numeric from location_code order by state_alpha;');
}
return $result;
}