Caching is one of the most effective ways to improve the performance and scalability of your Laravel application. By storing frequently accessed data in a fast-access storage layer, you can reduce database queries, speed up response times, and handle more traffic with fewer resources. In this guide, we’ll explore how to use caching in Laravel with a practical example using the ProductController.
1. What is Caching in Laravel?
Caching is the process of storing data temporarily in a high-speed storage layer (like memory) so that future requests for the same data can be served faster. Laravel provides a unified API for various caching backends, including:
File-based caching
Database caching
Redis
Memcached
In this guide, we’ll use Laravel’s caching system to store and retrieve a list of active products.
2. Setting Up the ProductController
Let’s start by creating a ProductController that demonstrates how to use caching in Laravel. The controller will have three methods:
index: Displays a list of active products, using caching to optimize performance.
create: Shows a form to create a new product.
store: Handles the creation of a new product and invalidates the cache.
Here’s the complete code for the ProductController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use App\Models\Product;
class ProductController extends Controller
{
/**
* Display a listing of the products.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
// Cache the list of active products forever
$products = Cache::rememberForever('active_products', function () {
return Product::where('active', 1)->get();
});
return view('products.index', compact('products'));
}
/**
* Show the form for creating a new product.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('products.create');
}
/**
* Store a newly created product in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
// Validate the request
$request->validate([
'name' => 'required|string|max:255',
'price' => 'required|numeric',
'active' => 'boolean',
]);
// Create the product
$product = Product::create([
'name' => $request->input('name'),
'price' => $request->input('price'),
'active' => $request->input('active', 1), // Default to active if not provided
]);
// Invalidate the cache
Cache::forget('active_products');
return redirect()->route('products.index')->with('success', 'Product created successfully!');
}
}
3. Breaking Down the Code
a. Caching Data with Cache::rememberForever
In the index method, we use the Cache::rememberForever method to cache the list of active products:
$products = Cache::rememberForever('active_products', function () {
return Product::where('active', 1)->get();
});
active_products: The cache key used to store the data.
Closure: The function that fetches the data from the database if the cache key doesn’t exist.
rememberForever: Stores the data in the cache indefinitely (or until manually removed).
This ensures that the database query is executed only once, and subsequent requests are served from the cache.
b. Invalidating the Cache
When a new product is created, the cache must be invalidated to ensure the updated list of products is displayed. In the store method, we use Cache::forget to remove the cached data:
Cache::forget('active_products');
This ensures that the next request to the index method will regenerate the cache with the updated data.
c. Displaying and Creating Products
The index method passes the cached products to the products.index view.
The create method displays a form to create a new product.
The store method validates the input, creates the product, and invalidates the cache.
4. Best Practices for Using Cache in Laravel
a. Choose the Right Cache Driver
Laravel supports multiple cache drivers. For high-performance applications, use Redis or Memcached. For smaller applications, file-based or database caching may suffice.
b. Use Cache Tags for Granular Control
If you’re using a cache driver that supports tags (e.g., Redis), you can group related cache items and clear them together:
Cache::tags(['products', 'active'])->rememberForever('active_products', function () {
return Product::where('active', 1)->get();
});
// Clear all cache items with the 'products' tag
Cache::tags(['products'])->flush();
c. Set Appropriate Cache Expiration
While rememberForever is useful for static data, most cached data should have an expiration time. Use Cache::remember with a time limit:
Cache::remember('active_products', 60, function () { // Cache for 60 minutes
return Product::where('active', 1)->get();
});
d. Monitor Cache Performance
Use tools like Laravel Telescope or Redis CLI to monitor cache usage and performance.
5. Benefits of Using Cache in Laravel
Improved Performance: Reduces database queries and speeds up response times.
Scalability: Handles more traffic with fewer resources.
Cost Efficiency: Reduces server load and infrastructure costs.
Better User Experience: Faster load times lead to happier users.
6. Conclusion
Caching is a powerful tool for optimizing Laravel applications. By implementing caching in your ProductController, you can significantly improve performance and scalability. Whether you’re caching database queries, API responses, or computed data, Laravel’s caching system makes it easy to get started.
In this guide, we covered:
How to cache data using Cache::rememberForever.
How to invalidate the cache when data changes.
Best practices for using cache in Laravel.
By following these steps, you can build faster, more efficient Laravel applications that scale effortlessly.
Next Steps
Explore Laravel’s documentation on caching: Laravel Caching
Experiment with different cache drivers (Redis, Memcached, etc.).
Implement caching in other parts of your application.
Top comments (0)