MCPInstall

laravel-caching-strategies

Best practices for Laravel caching including cache patterns, tags, atomic locks, flexible cache, and cache invalidation strategies.

Installs
93
Last 24h
—
Trending rank
—
Security
Not audited

Install

Works with every agent the skills CLI supports.

npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-caching-strategies
  1. 01

    Install

    Run the command in your project. The CLI asks which agents to install for.

  2. 02

    Describe the task

    Ask your agent for something this skill covers. It loads laravel-caching-strategies automatically when relevant.

  3. 03

    Review the result

    The agent follows the SKILL.md steps, scripts and references bundled with the skill.

SKILL.md

The instructions your agent reads when the skill is triggered.

Laravel Caching Strategies

Core Cache Patterns

use Illuminate\Support\Facades\Cache;

// ✅ remember - cache for a duration
$users = Cache::remember('users:active', now()->addMinutes(30), function () {
    return User::where('active', true)->get();
});

// ✅ rememberForever - cache until manually cleared
$settings = Cache::rememberForever('app:settings', function () {
    return Setting::all()->pluck('value', 'key');
});

// ✅ flexible - stale-while-revalidate pattern
// Fresh for 5 min, serves stale for up to 15 min while revalidating in background
$stats = Cache::flexible('dashboard:stats', [300, 900], function () {
    return DashboardStats::calculate();
});

// ✅ put / get / forget
Cache::put('key', $value, now()->addHours(1));
$value = Cache::get('key', 'default');
Cache::forget('key');

// ❌ Querying the database when cache would suffice
$settings = Setting::all(); // Every request hits the DB

Cache Tags for Grouped Invalidation

// ✅ Tag related cache entries
Cache::tags(['posts', 'users'])->put("user:{$userId}:posts", $posts, 3600);
Cache::tags(['posts'])->put("post:{$postId}", $post, 3600);
Cache::tags(['users'])->put("user:{$userId}:profile", $profile, 3600);

// ✅ Flush all caches for a tag group
Cache::tags(['posts'])->flush(); // Clears all post-related caches

// ✅ Retrieve tagged cache
$posts = Cache::tags(['posts', 'users'])->get("user:{$userId}:posts");

// Note: Cache tags are only supported by redis and memcached drivers

Atomic Locks

use Illuminate\Support\Facades\Cache;

// ✅ Prevent concurrent execution
$lock = Cache::lock('processing:order:' . $orderId, 10); // 10 second lock

if ($lock->get()) {
    try {
        // Process order exclusively
        $this->processOrder($orderId);
    } finally {
        $lock->release();
    }
}

// ✅ Block and wait for lock (up to 5 seconds)
$lock = Cache::lock('report:generate', 30);

$lock->block(5, function () {
    // Acquired lock, do work
    $this->generateReport();
}); // Lock auto-released after closure

// ✅ Cross-process lock with owner token
$lock = Cache::lock('deployment', 120);

if ($lock->get()) {
    $owner = $lock->owner();
    // Pass $owner to another process
}

// In the other process
Cache::restoreLock('deployment', $owner)->release();

// ❌ Forgetting to release locks
$lock->get();
$this->doWork(); // If this throws, lock is never released

Cache Memoization

use Illuminate\Support\Facades\Cache;

// ✅ memo - in-memory cache for the current request lifecycle
// Avoids repeated cache store lookups within the same request
$config = Cache::memo('app:config', function () {
    return Config::loadFromDatabase();
});

// Subsequent calls return the in-memory value without hitting Redis/Memcached
$config = Cache::memo('app:config', fn () => Config::loadFromDatabase());

Model Caching Patterns

class Product extends Model
{
    // ✅ Cache on read with automatic invalidation
    public static function findCached(int $id): ?self
    {
        return Cache::remember(
            "product:{$id}",
            now()->addHour(),
            fn () => static::find($id)
        );
    }

    // ✅ Invalidate cache on model changes
    protected static function booted(): void
    {
        static::saved(function (Product $product) {
            Cache::forget("product:{$product->id}");
            Cache::tags(['products'])->flush();
        });

        static::deleted(function (Product $product) {
            Cache::forget("product:{$product->id}");
            Cache::tags(['products'])->flush();
        });
    }
}

// ✅ Cache query results with tags for group invalidation
class ProductService
{
    public function getFeatured(): Collection
    {
        return Cache::tags(['products'])->remember(
            'products:featured',
            now()->addMinutes(30),
            fn () => Product::where('featured', true)->with('category')->get()
        );
    }
}

Cache Key Conventions

// ✅ Use consistent, descriptive key patterns
"user:{$userId}:profile"
"post:{$postId}:comments:page:{$page}"
"tenant:{$tenantId}:settings"
"api:github:repos:{$username}"
"report:daily:{$date}"

// ✅ Include cache-busting identifiers when data shape changes
"v2:user:{$userId}:profile"

// ❌ Vague or collision-prone keys
"data"
"user"
"temp"
"cache_1"

Common Pitfalls

// ❌ Caching null results without handling them
$user = Cache::remember("user:{$id}", 3600, fn () => User::find($id));
// If user doesn't exist, null is cached for an hour

// ✅ Handle null explicitly
$user = Cache::remember("user:{$id}", 3600, function () use ($id) {
    return User::find($id) ?? new NullUser();
});

// ❌ No invalidation strategy
Cache::forever('products:all', Product::all());
// Data becomes stale with no way to refresh

// ✅ Use TTL or event-based invalidation
Cache::remember('products:all', now()->addMinutes(15), fn () => Product::all());

// ❌ Caching too aggressively (serialization cost > query cost)
Cache::remember('user:count', 3600, fn () => User::count());
// Simple COUNT queries are often fast enough without caching

// ✅ Cache expensive operations
Cache::remember('dashboard:analytics', 3600, function () {
    return DB::table('orders')
        ->selectRaw('DATE(created_at) as date, SUM(total) as revenue')
        ->groupByRaw('DATE(created_at)')
        ->orderBy('date')
        ->get();
});

// ❌ Cache stampede - many requests regenerate cache simultaneously
// ✅ Use flexible() for stale-while-revalidate or atomic locks for regeneration

Checklist

  • remember/rememberForever used instead of manual get/put
  • flexible() used for high-traffic keys that tolerate brief staleness
  • Cache tags used for grouped invalidation (Redis/Memcached only)
  • Atomic locks used for exclusive operations
  • Model caches invalidated on save/delete events
  • Cache keys follow a consistent naming convention
  • TTLs set appropriately (not too long, not too short)
  • Null/empty results handled to avoid caching nothing
  • Expensive queries cached, trivial queries left uncached
  • Cache stampede prevented with flexible() or locks

FAQ

What does the laravel-caching-strategies skill do?

Best practices for Laravel caching including cache patterns, tags, atomic locks, flexible cache, and cache invalidation strategies.

How do I install laravel-caching-strategies?

Run npx skills add https://github.com/iserter/laravel-claude-agents --skill laravel-caching-strategies in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/laravel-caching-strategies/ (personal) or .claude/skills/laravel-caching-strategies/ (project).

Which AI agents can use laravel-caching-strategies?

Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.

Is laravel-caching-strategies safe to install?

No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.

Who maintains laravel-caching-strategies?

It is published by iserter in iserter/laravel-claude-agents. It has 93 recorded installs.

More from iserter/laravel-claude-agents

View all →

eloquent-best-practices

iserter/laravel-claude-agents

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

laravel-tdd

iserter/laravel-claude-agents

Test-Driven Development specifically for Laravel applications using Pest PHP. Use when implementing any Laravel feature or bugfix - write the test first, watch it fail, write minimal code to pass.

Backend & APIs378 installs

laravel-blade-component-patterns

iserter/laravel-claude-agents

Best practices for Laravel Blade components including class-based and anonymous components, slots, attribute bags, and reusable UI patterns.

Backend & APIs116 installs

api-resource-patterns

iserter/laravel-claude-agents

Open the skill to read its SKILL.md instructions.

Backend & APIs110 installs

laravel-systematic-debugging

iserter/laravel-claude-agents

Systematic debugging process for Laravel applications - ensures root cause investigation before attempting fixes. Use for any Laravel issue (test failures, bugs, unexpected behavior, performance problems).

Backend & APIs102 installs

laravel-validation-patterns

iserter/laravel-claude-agents

Best practices for Laravel validation including Form Requests, custom rules, conditional validation, and input sanitization.

Backend & APIs100 installs

Popular backend & apis skills

View category →

find-skills

vercel-labs/skills

Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill.

OfficialBackend & APIs4.1M installs

entra-app-registration

microsoft/azure-skills

Guides Microsoft Entra ID app registration, OAuth 2.0 authentication, and MSAL integration. USE FOR: create app registration, register Azure AD app, configure OAuth, set up authentication, add API permissions, generate service principal, MSAL example, console app auth, Entra ID setup, Azure AD authentication. DO NOT USE FOR: Key Vault secrets (use azure-keyvault-expiration-audit), general Azure resource security guidance.

OfficialBackend & APIs566.7K installs

This skill should be used when the user wants to "write agent code", "build an agent with ADK", "add a tool", "create a callback", "define an agent", "use state management" — in a project that needs ADK (Agent Development Kit) API patterns and code examples. It provides a quick reference for agent types, tool definitions, orchestration patterns, callbacks, state management, the graph Workflow API, and reference recipes to study. Do NOT use for scaffolding (use google-agents-cli-scaffold) or deployment (use google-agents-cli-deploy).

Backend & APIs514.8K installs

embedded-captions

heygen-com/hyperframes

Add captions or subtitles to an existing single-subject talking-head video without editing the footage. Use for plain verbatim captions, cinematic captions embedded behind the subject, VFX captions, “炸/特效/酷炫字幕,” or a named identity from the 35-style catalog. Route by visual identity, not by backend engine. The quiet anchor rail is the default; embed every word only when the user explicitly wants a fully cinematic treatment. The workflow runs locally end to end, including transcription and subject matting; split multi-shot footage before applying it.

Backend & APIs453.3K installs

entra-agent-id

microsoft/azure-skills

Provision Microsoft Entra Agent Identity Blueprints, BlueprintPrincipals, and per-instance Agent Identities via Microsoft Graph, and configure OAuth 2.0 token exchange (fmipath, OBO, cross-tenant) including the Microsoft Entra SDK for AgentID sidecar. USE FOR: Agent Identity Blueprint, BlueprintPrincipal, agent OAuth, fmipath token exchange, agent OBO, Workload Identity Federation for agents, polyglot agent auth, Microsoft.Identity.Web.AgentIdentities. DO NOT USE FOR: standard Entra app registration (use entra-app-registration), Microsoft Foundry agent authoring (use microsoft-foundry).

OfficialBackend & APIs336.6K installs

neon

neondatabase/agent-skills

Overview of Neon, a complete set of cloud backend primitives around Lakebase Postgres: Auth, Object Storage, Functions, the AI Gateway, and Realtime. Start here to choose Neon for undecided login, files, APIs, and LLM calls, set up the CLI or MCP server, and follow the branch-first workflow. Use when building an app or backend on Neon, or when "Neon" or "Lakebase Postgres" is mentioned. Child skill neon-postgres wins for an existing DATABASEURL, SQL, schema, inspect, or search. Child skill neon-auth wins for login, users, sessions, identity routing, and Managed Better Auth setup. Child skill neon-realtime wins for live queries in reactive apps and agents. Also use for object storage, S3, buckets, serverless functions, function triggers, cron, AI gateway, LLM calls, realtime, logs, Loki, Grafana, observability, postgres, database, backend, Claimable Neon, neon.new, or a no-signup database.

Backend & APIs237.1K installs