Caching in Laravel

Lesson 40 of 50

80%
1. What Is Caching in Laravel?

Caching is a technique used to store frequently accessed data temporarily so that an application can retrieve it faster instead of performing the same expensive operation repeatedly.

Examples of caching:

  • Storing frequently used student records.
  • Caching course lists.
  • Reducing repeated database queries.
  • Storing dashboard statistics.
  • Caching API responses or calculated results.

Laravel provides a convenient Cache facade for storing, retrieving, and removing cached values.

Example without caching:

$students = Student::all();

Every time this statement runs, Laravel queries the database.

Example with caching:

$students = Cache::remember(
    'students',
    300,
    function () {
        return Student::all();
    }
);

Laravel stores the result for 300 seconds. During that period, subsequent requests can reuse the cached value.

2. Configure the Cache Driver

Laravel supports several cache stores, including database, file, Redis, and other supported backends.

The exact environment variable and default cache store depend on your Laravel version and project configuration. Check your .env file and config/cache.php.

For a file-based cache, a typical configuration is:

CACHE_STORE=file

Some older Laravel versions use CACHE_DRIVER instead.

For a database cache, configure the database store according to your Laravel version and create its required table if it does not already exist.

Check available Artisan commands:

php artisan list

After changing environment settings, clear cached configuration when necessary:

php artisan config:clear
3. Store and Retrieve Cached Data

Use the Cache facade to store a value and retrieve it later.

Import the facade:

use Illuminate\Support\Facades\Cache;

Store a value:

Cache::put('college_name', 'Soopro Pathshala', 600);

The value is stored for 600 seconds, or 10 minutes.

Retrieve the value:

$collegeName = Cache::get('college_name');

echo $collegeName;

Expected output:

Soopro Pathshala

Retrieve a value with a default:

$name = Cache::get('college_name', 'Default College');

If the key does not exist or its cached value has expired, Laravel returns the supplied default.

4. Use Cache::remember()

Cache::remember() is useful when you want Laravel to retrieve a cached value or calculate and cache it when the value is missing.

Example using a Student model:

<?php

namespace App\Http\Controllers;

use App\Models\Student;
use Illuminate\Support\Facades\Cache;

class StudentController extends Controller
{
    public function index()
    {
        $students = Cache::remember(
            'students',
            300,
            function () {
                return Student::orderBy('name')->get();
            }
        );

        return response()->json([
            'data' => $students,
        ]);
    }
}

How it works:

  1. Laravel checks whether the key students exists.
  2. If the value exists, Laravel returns the cached data.
  3. If it is missing or expired, the callback executes.
  4. The callback result is cached for 300 seconds.

This can reduce repeated database queries for frequently requested data that does not change constantly.

5. Remove and Clear Cached Data

When data changes, you may need to remove cached values so that users do not continue seeing outdated information.

Remove one cache key:

Cache::forget('students');

Check whether a key exists:

if (Cache::has('students')) {
    echo 'Student data is cached.';
}

Clear the current cache store:

Cache::flush();

Be careful with Cache::flush(): it removes all items from the selected cache store and does not respect individual cache prefixes.

In most applications, prefer removing specific keys instead of clearing the entire cache.

6. Cache Student Records After Updates

Suppose your application caches all students. When a student is added or updated, remove the relevant cached value so the next request loads fresh data.

Example controller method for creating a student:

use App\Models\Student;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

public function store(Request $request)
{
    $validated = $request->validate([
        'name' => ['required', 'string', 'max:255'],
        'email' => ['required', 'email', 'max:255', 'unique:students,email'],
        'course' => ['required', 'string', 'max:255'],
    ]);

    $student = Student::create($validated);

    Cache::forget('students');

    return response()->json([
        'message' => 'Student created successfully.',
        'data' => $student,
    ], 201);
}

Use the same cache key consistently in the method that reads the student list and in the methods that modify it.

If your application caches individual students or multiple filtered lists, invalidate those keys as well.

7. Cache Dashboard Statistics

Dashboard statistics can involve expensive database queries. Caching these calculations can improve response times.

Example controller method:

use App\Models\Student;
use Illuminate\Support\Facades\Cache;

public function dashboard()
{
    $totalStudents = Cache::remember(
        'dashboard.total_students',
        300,
        function () {
            return Student::count();
        }
    );

    return response()->json([
        'total_students' => $totalStudents,
    ]);
}

Laravel caches the student count for five minutes. During that period, the application can avoid repeating the count query on every request.

Useful dashboard cache keys:

  • dashboard.total_students
  • dashboard.total_courses
  • dashboard.monthly_fees
  • dashboard.pending_payments

For financial and administrative data, choose an appropriate expiration time and invalidate cached values whenever relevant records change.

8. Cache Best Practices
  • Choose meaningful and unique cache keys.
  • Set expiration times appropriate for the data.
  • Invalidate cached data after relevant updates.
  • Avoid caching sensitive information unnecessarily.
  • Include user or tenant identifiers in keys when data is user-specific.
  • Monitor cache performance and storage usage.
  • Use Redis or another suitable store when your application needs it.
  • Do not assume cached data is always current.

Important:

Caching is not a replacement for database validation, authentication, or authorization. Never rely on a cached permission or account status without considering how quickly it must reflect changes.

9. Practice Assignment

Complete the following practical tasks:

  1. Store a college name using Cache::put().
  2. Retrieve it using Cache::get().
  3. Use Cache::remember() to cache a student list.
  4. Create a dashboard method that caches the student count.
  5. Remove the student-list cache after adding a student.
  6. Test what happens when a cached value expires.
  7. Compare repeated database queries with cached requests.

Bonus Task:

Cache the total number of students and total number of courses on an admin dashboard. Invalidate the appropriate keys when students or courses are added, updated, or deleted.

Quick Quiz

1. What is the main purpose of caching?




2. Which method retrieves a cached value or calculates and stores it when missing?




3. Which method removes one specific cache key?