Caching in Laravel with Redis
Project Setup
Create a new Laravel application:
Database Setup
Create a Redis database using Upstash Console. Go to the Connect to your database section and click on Laravel. Copy those values into your .env file:
Cache Setup
To use Upstash Redis as your caching driver, update the CACHE_STORE in your .env file:
Creating a Todo App
First, we’ll create a Todo model with its associated controller, factory, migration, and API resource files:
Next, we’ll set up the database schema for our todos table with a simple structure including an ID, title, and timestamps:
We’ll create a factory to generate fake todo data for testing and development:
In the database seeder, we’ll set up the creation of 50 sample todo items:
Run the migration to create the todos table in the database:
Seed the database with our sample todo items:
Install the API package:
Set up the API routes for our Todo resource:
Create a basic Todo controller with an index method to retrieve all todos:
Finally, test the index route to verify our API is working correctly:
Using Cache in Laravel
Laravel offers a simple yet powerful unified interface for working with different caching systems. We will focus on Cache::remember
, Cache::flexible
and Cache::forget
methods, to learn more about the available methods, check the Laravel Cache Documentation.
Cache::remember
The Cache::remember
method retrieves the value of a key from the cache. If the key does not exist in the cache, the method will execute the given closure and store the result in the cache for the specified duration.
Cache::flexible
The stale-while-revalidate pattern, implemented through Cache::flexible
, is a caching strategy that balances performance and data freshness by defining two time periods: a “fresh” period where cached data is served immediately, and a “stale” period where outdated data is served while triggering a background refresh. When data is accessed during the stale period (in this example, between 5 and 10 seconds), users still get a fast response with slightly outdated data while the cache refreshes asynchronously, only forcing users to wait for a full recalculation if the data is accessed after both periods have expired.
Cache::forget
The Cache::forget
method removes the specified key from the cache:
Caching the Todo List
Let’s first update the Todo model to make it mass assignable:
Next, we’ll update the methods in the TodoController to use caching:
Now we can test our methods with the following curl commands:
Visit Redis Data Browser in Upstash Console to see the cached data.
Was this page helpful?