Easily Cache Eloquent Collections

I found an article by Mark van Eijk that outlines how to easily cache Eloquent results by using the following syntax:

$articles = Article::with('comments')->remember(5)->get();

I wanted to point out that in the event you want to cache all articles, the following syntax doesn’t work

$articles = Article::all()->remember(5); // doesn't work

What you need to do instead is the following:

$articles = Article::remember(5)->get(); // works great!

You can verify the query is not run on subsequent requests by dd’ing the queries that were run during the request:


Hope this helps someone! If you have any Laravel tricks of your own post them in the comments below.

Made with ❤ by Chris Hayes