Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cache all records from query in laravel 5

I'm trying to cache all records of the query for 60 minutes by the following method (Method 1)

Route::get('categoryList', function() {
   return app\CategoryDetails::remember(60)->get();
});

I followed this tutorial link (Tip 5: Cache Database Queries)

But I'm getting this error:

Call to undefined method Illuminate\Database\Query\Builder::remember()

I don't know what I'm missing here.

BTW, I know I can cache entire records by the following method (Method 2):

Route::get('categoryList', function() {    
    $category = Cache::remember('category', 10, function() {
        return \App\CategoryDetails::all();
    });

    return $category;
});

and this is working perfectly.

I am just curious why the first method is not working for me.

like image 848
Muhammed Khalander Avatar asked Sep 22 '15 14:09

Muhammed Khalander


2 Answers

Laravel 5 removed this functionality. You now have to store the cache yourself:

Route::get('categoryList', function () {
    return Cache::remember('category-details', 60, function () {
        return App\CategoryDetails::all();
    });
});

From the upgrade docs:

Eloquent no longer provides the remember method for caching queries. You now are responsible for caching your queries manually using the Cache::remember function.

like image 97
Joseph Silber Avatar answered Oct 01 '22 05:10

Joseph Silber


Consider using a laravel eloquent query caching library called rememberable

It does a pretty good job.

like image 23
Cengkuru Michael Avatar answered Oct 01 '22 05:10

Cengkuru Michael