Lesson 40 of 50
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:
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.
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
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.
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:
students exists.This can reduce repeated database queries for frequently requested data that does not change constantly.
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.
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.
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_studentsdashboard.total_coursesdashboard.monthly_feesdashboard.pending_paymentsFor financial and administrative data, choose an appropriate expiration time and invalidate cached values whenever relevant records change.
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.
Complete the following practical tasks:
Cache::put().Cache::get().Cache::remember() to cache a student list.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.
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?