agyanadda@gmail.com

Laravel Caching

Advanced Laravel 1 min read Updated Dec 2, 2026 Topic 28 of 31

Caching stores the result of slow work (database queries, API calls) so the next request can reuse it instantly.

Cache drivers

Set the driver in .env (CACHE_STORE in Laravel 11+, CACHE_DRIVER in older versions):

  • file — simple, works everywhere
  • database — stores in the cache table
  • redis / memcached — fastest, for busy sites

Basic use

  • Cache::put('key', $value, now()->addMinutes(10)) — store for 10 minutes
  • Cache::get('key', 'default') — read
  • Cache::has('key'), Cache::forget('key')
  • Cache::forever('key', $value) — no expiry

Cache::remember — the most useful one

Cache::remember('key', $seconds, fn () => ...) returns the cached value if it exists; otherwise it runs the function, stores the result and returns it.

Keep the cache fresh

When data changes (a post is saved), call Cache::forget('key') so visitors do not see old data.

Framework caches

On the live server, php artisan optimize caches config, routes and views for faster loading. php artisan cache:clear empties the app cache.

Example

Example — Cache the homepage posts PHP
<?php
use Illuminate\Support\Facades\Cache;

// HomeController
public function index()
{
    $posts = Cache::remember('home.latest-posts', now()->addMinutes(30), function () {
        return Post::published()->with('user')->latest()->take(10)->get();
    });

    return view('home', compact('posts'));
}

// PostController@store / update / destroy — clear it when posts change
Cache::forget('home.latest-posts');

The first visitor runs the query; for the next 30 minutes every visitor gets the cached list with no database query. Saving a post clears the cache, so the change appears immediately.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which method returns the cached value or runs a function to create it?

Exercise 2 True / False

You should clear related cache keys when the underlying data changes.

Exercise 3 Fill in the Blank

Remove one item from the cache with Cache::___('key').

Frequently Asked Questions

Cache data that is read often and changes rarely: homepage lists, menus, categories, settings, counts and results from external APIs. Do not cache personal data under a shared key, or one user may see another user's data.