Forget Cache Automatically on Save Mood in Laravel

Hello Artisan I came again with a brand new tips for all of you. Today i am going to show you a magical thing which you called it Laravel tips and trics. Now i will show you that how you can forget cache key when you save a new record on your specific model. 

Laravel provide many types of way to solve this problem. So in this example i will show you a very simple and easy to captured and a magical thing. you have to add just couple of lines code in your model that has to be forgotten cache key when you are going to save a new record.

Sometimes we can use event listener to do thing thing. Actually this is developer demand and how they think. But i will show you a simple thng to remove your past cache data from your cache key using Laravel boot method. See the example code to forget cache key in Laravel.

App\Models\Post.php

class Post extends Model
{
    // Forget cache key on storing or updating
    public static function boot()
    {
        parent::boot();
        static::saving(function () {
           Cache::forget('posts');
        });
    }
}

 

Read also : Load Relationships Always, but Dynamically in Laravel

 

Hope it can help you.