Query Cache in Laravel

A query cache is a cache of the results of a database query. Laravel has an inbuilt query cache that can be used to store the results of queries. When you run a query, Laravel checks the query cache first and if it finds the result there, it returns it immediately without running the query again.

Query Cache

use Illuminate\Support\Facades\Cache;

This will retrieve data from the cache article_list but it's the cache article_list not exists it will get the data from the database and store it in to cache forever.

public function articleList()
{
    $articles = Cache::rememberForever('article_list', function() {
        return DB::table('articles')
            ->select(
                'articles.title as title',
                'articles.content as content'
            )
            ->get();
    });
    return view('article_page', ['articles' => $articles]);
}

This will retrieve data from the cache article_list but it's the cache article_list not exists it's will get the data from database and store it to cache 60 second.

public function articleList()
{
    $articles = Cache::remember('article_list', 60, function() {
        return DB::table('articles')
            ->select(
                'articles.title as title',
                'articles.content as content'
            )
            ->get();
    });
    return view('article_page', ['articles' => $articles]);
}

Remove cache

If you use DB query to update, create, or delete you can use this to clear the cache on action

Cache::forget('article_list');

For eloquent you can create this to model for clear cache on creating, updating, deleting

public static function boot()
{
    parent::boot();
    static::creating(function() {
        Cache::forget('article_list');
    });

    static::updating(function() {
        Cache:forget('article_list');
    });
        
    static::deleting(function() {
        Cache::forget('article_list');
    });
}