Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ga46's avatar
Level 1

laravel Cache.

i want to Cache my data and if i change my value in database than cache will automatically update and if not change than not query in database and return data to Cache.

suppose i Cache my data [1,2,3,4] this array after 5 minutes i update my data [1,2,3,4,5,6] now how i get my latest update data .

note: if data is update than only query database if not change not query to database.

0 likes
7 replies
MohamedTammam's avatar

Add a cache every time you update your data

$yourData = ...; // Your logic of getting your data
Cache::forever('your-key',  $yourData);

You need to handle when you store your new values yourself.

tisuchi's avatar

@ga46 I am just elaborating @mohamedtammam idea.

In Laravel, you can cache data using the built-in caching system. Here is an example of how you can cache your data and automatically update it if it changes:

$data = Cache::remember('data', 5, function () {
    return [1, 2, 3, 4];
});

if (something changes in your database) {
    Cache::forget('data');
    $data = [1, 2, 3, 4, 5, 6];
    Cache::put('data', $data, 5);
}

return $data;

The remember method will check if there is a cache entry with the key data. If it exists, it will return the cached data. If not, it will execute the closure and cache the result for 5 minutes.

The forget method deletes a cache entry with the specified key. In this example, we are deleting the data cache entry if something changes in the database.

Finally, the put method caches the updated data for 5 minutes.

This way, you will always get the latest data, while avoiding unnecessary database queries when the data has not changed.

ga46's avatar
Level 1

@tisuchi i dont agree this point if if (something changes in your database) .others alternative way any idea? with this

$data = Cache::remember('data', 5, function () {
    return [1, 2, 3, 4];
});
tisuchi's avatar

@ga46 You mentioned this, right?

suppose i Cache my data [1,2,3,4] this array after 5 minutes i update my data [1,2,3,4,5,6] now how i get my latest update data .

I don't know why you don't agree.

Sinnbeck's avatar

I assume it's not just a few ids you are caching, but rather some huge complex operation that takes time. So I would suggest using model events and dispatch a queued job that can recalculate and update the cache

ga46's avatar
Level 1

@Sinnbeck its just an example here .but we have complex query to get ids .Thats why i want to cache query.

malsowayegh's avatar

you will need to do it manually. There is no magic way that Laravel can do it for you. you will need to manage when to store, forget or even update your cache

Please or to participate in this conversation.