Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you forget cached Eloquent models in Laravel?

Theoretical question on Laravel here.

So Example of the caching I'd do is:

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

Ideally I'd like to have an event for Article updates that when the ID of a instance of that model (that's already cached) is updated I want to forget that key (even if it's the whole result of the query that's forgotten instead of just that one model instance), it is possible to do so?

If not is there some way to implement this reasonably cleanly?

like image 929
Peter Fox Avatar asked Oct 23 '13 13:10

Peter Fox


People also ask

How do I clear the cache in Laravel on a server?

The following is the syntax to clear cache in Laravel is given below: php artisan cache: clear. php artisan config: clear. php artisan cache: clear.

What is cache memory in Laravel?

By default, Laravel is configured to use the file cache driver, which stores the serialized, cached objects in the filesystem. For larger applications, it is recommended that you use an in-memory cache such as Memcached or APC. You may even configure multiple cache configurations for the same driver.


1 Answers

So i was looking for an answer to the same question as OP but was not really satisfied with the solutions. So i started playing around with this recently and going through the source code of the framework, I found out that the remember() method accepts second param called key and for some reason it has not been documented on their site (Or did i miss that?).

Now good thing about this is that, The database builder uses the same cache driver which is configured under app/config/cache.php Or should i say the same cache system that has been documented here - Cache. So if you pass min and key to remember(), you can use the same key to clear the cache using Cache::forget() method and in fact, you can pretty much use all the Cache methods listed on the official site, like Cache::get(), Cache::add(), Cache::put(), etc. But i don't recommend you to use those other methods unless you know what you're doing.

Here's an example for you and others to understand what i mean.

Article::with('comments')->remember(5, 'article_comments')->get();

Now the above query result will be cached and will be associated with the article_comments key which can then be used to clear it anytime (In my case, I do it when i update).

So now if i want to clear that cache regardless of how much time it remembers for. I can just do it by calling Cache::forget('article_comments'); and it should work just as expected.

Hope this helps everyone :)

like image 196
Syed I.R. Avatar answered Sep 24 '22 17:09

Syed I.R.