ricovzelst's avatar

Caching Eloquent Queries?

Good afternoon all,

I'm working on a little side-project, and I'd like to cache Eloquent Queries, my database data barely ever changes. It might change every 12 hours, but it's only a slight chance. However, it does have a good amount of entries (200k+) So I'd like to cache my queries to Eloquent. I read about the existence of remember() but it has since been removed, there is a package (laravel-eloquent-query-cache) that adds it back, but I'm wondering what the reason for removal was before I use a package adding it back.

Any advice would be appreciated.

0 likes
7 replies
LaryAI's avatar
Level 58

The remember() method was removed from Laravel because it was not being used frequently and had some limitations. However, you can achieve query caching in Laravel using the cache() method and the remember() method from the Illuminate\Support\Facades\Cache class.

Here's an example of how you can cache an Eloquent query using the cache() and remember() methods:

use Illuminate\Support\Facades\Cache;

$users = Cache::remember('users', 60 * 12, function () {
    return User::all();
});

In this example, the users key is used to cache the result of the User::all() query for 12 hours (60 minutes * 12). If the data is already cached, it will be retrieved from the cache. Otherwise, the query will be executed, and the result will be stored in the cache for future use.

You can adjust the cache duration according to your needs. Additionally, you can use different cache drivers (e.g., file, database, Redis) by configuring the CACHE_DRIVER option in your .env file.

Remember to import the Cache facade at the top of your file:

use Illuminate\Support\Facades\Cache;

I hope this helps! Let me know if you have any further questions.

2 likes
ricovzelst's avatar

@Snapey I got confused when googling about this as remember() was removed, but only out of Eloquent itself. E.g. you used to be able to do $users = User::remember(60)->get();

Thanks for the help.

1 like
kevinbui's avatar

I don't find retrieving 200k records at once, or even caching them, is a good idea. Because this error will occur.

What about pagination? Or only filter a handful of records?

1 like

Please or to participate in this conversation.