theGreenCabbage theGreenCabbage - 6 months ago 42
PHP Question

Caching scope queries in Laravel

I am trying to implement Cache into my Laravel 5.0 project

Many of the examples I see online for caching are not scope queries, so I am a little confused. Here is a query/method from my Model that returns all my classes' concatenations of

subject_code
and
course_no


/**
* Get all course codes and titles
* Used in the autocomplete search
* @param $query
* @return mixed
*/
public function scopeAllCourseNo($query) {
return $query
->orderBy('course_no')
->groupBy(
DB::raw("subject_code || ' ' || course_no")
)
->get()
;
}


As the first line of the method is simply a return, I am curious as to where I can put the
Cache::add('', $allClasses, 30);
query? And where do I put:

if (Cache::has('allClasses'))
{
return Cache::get('allClasses');
}


Thank you very much.

Answer

You don't cache in your model. You cache in your controller.

So in your controller:

You can use Cache add(), but I prefer Cache::remember(). https://laravel.com/api/5.2/Illuminate/Cache/Repository.html#method_remember

$classes = Cache::remember('classes', 60, function() {
    return Class::allCourseNo()->get();
});