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:.env
Cache Setup
To use Upstash Redis as your caching driver, update the CACHE_STORE in your .env file:.env
Creating a Todo App
First, we’ll create a Todo model with its associated controller, factory, migration, and API resource files:database/migrations/2025_02_10_111720_create_todos_table.php
database/factories/TodoFactory.php
database/seeders/DatabaseSeeder.php
routes/api.php
app/Http/Controllers/TodoController.php
Using Cache in Laravel
Laravel offers a simple yet powerful unified interface for working with different caching systems. We will focus onCache::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:app/Models/Todo.php
app/Http/Controllers/TodoController.php