Jaylen Jaylen - 1 year ago 210
PHP Question

When does Laravel clear the cache?

I am trying to utilize

with Laravel 5 to cache queries/results to make my application run faster.

However, I have couple of questions which should help me decide when it is a good time to use
and when it is not.

Assume I have the following

$interview= Cache::remember('SomeUniqueKey', 180, function(){

return SurveyInterview::where('user_id', 123)

The previous code should cache the collection set returned by eloquent. which is a total of 3 queries. First to query the model, second to query the
relation and the last one to query the

It is my understanding that as long as I execute the above code over and over, Laravel will return the collection from the cache until the 180 minutes are up from the time the collection was cached.


Will laravel automatically remove the cache if an update took place to my database tables? In other works, will it remove the cache once I make an update to my
model or will I have to remove that manually every time I update the model?

Answer Source

The answer to this really depends on what cache driver is being used.

For drivers like Memcache or APC, those services know how to "garbage collect" themselves and automatically flush expired entries.

For the File driver, it relies on the the UNIX timestamp of the file creation to determine if it has expired. The file is not deleted until an attempt to retrieve it occurs and it is determined to be expired

For the Database driver, it stores an expiration column and can determine how if it is expired from that timestamp. The record is not automatically deleted upon expiration -- only when an attempt to get the cache entry occurs and it is found to be expired (similar to the file driver).

To answer the overarching question, you are correct that remember() will continue to retrieve it from the cache until it expires. It does that by calling the get() method on the specific storage class, which in the case of file and database, will flush the entries if expired automatically. When it returns no entry due to expiration, your closure logic will execute to generate a fresh set of data.

As far as I am aware, no, it will not flush the cache when an update occurs. A quick search of the Illuminate\Database folder for forget or flush does not indicate that it would do that. That being said, you can detect when an update occurs with model events and have it flush the cache fairly easily by adding something like this to the model.

public function boot()
    SurveyInterview::updated(function ($survey) {
        app('cache')->forget('my-survey-key-' . $survey->id);


FileStore: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Cache/FileStore.php

DatabaseStore: https://github.com/laravel/framework/blob/5.2/src/Illuminate/Cache/DatabaseStore.php#L66


Redis, like Memcache and APC, handle the flush on their own. For example, see this: