Vivek Mistry 👋

I’m a Certified Senior Laravel Developer with 6+ years of experience , specializing in building robust APIs and admin panels, frontend templates converting them into fully functional web applications.

Book A Call
  • 16 Oct, 2025
  • 539 Views
  • Keep your category list always fresh and fast by updating cache automatically on create, edit, or delete.

Speed Up Your Laravel App by Caching Categories Automatically

Introduction

Fetching categories from the database every time a page loads might sound simple, but it quickly becomes a performance bottleneck—especially when your app grows or traffic spikes.

Laravel provides a clean solution to this: caching your categories, and automatically refreshing that cache whenever a category is created, updated, or deleted.

In this guide, we’ll see how to implement it step-by-step so your categories always load instantly without stale data.

Step 1: Cache Categories When Needed

use Illuminate\Support\Facades\Cache;
use App\Models\Category;
$categories = Cache::rememberForever('categories', function () {
    return Category::orderBy('name')->get();
});

Explanation

  • rememberForever stores the categories indefinitely until manually cleared.
  • The closure runs only once—the first time cache is empty.
  • After that, categories are fetched directly from cache (no DB hit).

Step 2: Automatically Refresh Cache on Create, Update, or Delete

Whenever a category changes, we need to refresh the cache.

You can handle this easily in the Category model’s events.

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;
class Category extends Model
{
    protected static function booted()
    {
        static::created(fn() => self::refreshCache());
        static::updated(fn() => self::refreshCache());
        static::deleted(fn() => self::refreshCache());
    }
    public static function refreshCache()
    {
        Cache::forget('categories');
        Cache::rememberForever('categories', function () {
            return self::orderBy('name')->get();
        });
    }
}

What this does:

  • When any category is added, edited, or removed, cache is cleared.
  • Immediately repopulates with the latest data.
  • Your frontend always gets fresh, up-to-date categories—without extra DB load.

Step 3: Use Cached Categories Everywhere

$categories = Cache::get('categories');

Or better yet, use a global helper or a view composer:

View::composer('*', function ($view) {
    $view->with('categories', Cache::get('categories'));
});

Pro Tip: Use Tags (Optional)

If you have multiple cache sections, you can use cache tags for better grouping:

Cache::tags(['categories'])->rememberForever('all', function () {
    return Category::all();
});
Cache::tags(['categories'])->flush(); // to clear all related cache


Share: