Home » Php » php – Caching, best practices

php – Caching, best practices

Posted by: admin February 25, 2020 Leave a comment


I have some questions about caches.

I use Laravel as a framework, and I never know how much times I should set up for the cache remember.

I mean, I used to create cache like this for example :

$model = Cache::remember("model.1", 60*24, function () {
      return Model::find(1)->first();

So here, I leave in cache for 1 day the model with the ID 1 for the key model.1

The question is, how much times I should set in cache. Usually, with this cache method, I add a ModelObserver which will forget the cache depending on the model ID if it has been deleted.
And will reput in cache for the model ID the request when the model has been updated or a model has been saved.

I could set infinite times in cache for the model so ? Because, the observer will add again in cache if needed or forget if needed (thanks to the observer)

I tried to find on the internet an article talking about cache times and how much should I set etc.. but I couldn’t find one.

And for example, I can have a cache that lists all the users of my application, if an user has been added (thanks to observer), I reput in cache the request to list all users (or forget it, and when the first user comes in the page which lists users, it’ll recache it).

What are the best practices concerning caches ?

Best regards

How to&Answers:

I would probably advice against caching User records – simply because of potential security issues you might run into.

What you’re doing looks absolutely fine and as you say, you can really push it to as long as it takes – if your Observer takes care of clearing it or re-caching then you already have the mechanism for managing it in place.

One thing I would probably change is the way you set the lifetime – you could use Illuminate\Support\Carbon like so for instance:

$model = Cache::remember("model.1", Carbon::now()->addYear(), function () {
      return Model::find(1)->first();

One other thing to take under consideration is the cache driver and the amount of storage you have available – redis stores everything in memory, file on the disk etc.

Other than that it all looks good.