theGreenCabbage theGreenCabbage - 5 months ago 31x
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


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

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.


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().

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