Understanding the Cache
Caching stores frequently accessed data in a faster-to-retrieve location, reducing the need for expensive computations or database queries on subsequent requests. In Laravel, you can cache:
Database queries: Eliminate redundant calls to the database by storing the results in memory.
Rendered views: Pre-render frequently accessed views and serve them directly, bypassing the rendering process.
Objects: Cache complex objects that involve expensive processing for faster retrieval.
Database Queries:
Laravel provides a fluent query builder and an Eloquent ORM for database interactions. You can cache the results of database queries to avoid hitting the database unnecessarily. The remember
method is commonly used for this purpose:
$users = Cache::remember('users', $minutes, function () {
return DB::table('users')->get();
});
Rendered Views:
Laravel allows you to cache the output of views, which can be beneficial for frequently accessed pages. You can use the cache
method in your routes or controllers to cache the rendered views:
return cache()->remember('my.view', $minutes, function () {
return view('my.view');
});
Objects:
You can cache arbitrary data, including complex objects, using the cache system. For example:
$myObject = new ExpensiveObject();
// Store in cache
Cache::put('my_object', $myObject, $minutes);
// Retrieve from cache
$cachedObject = Cache::get('my_object');
Caching Frequently Used Calculations:
Often, applications perform complex calculations or aggregations based on frequently accessed data. Caching the calculated results can significantly improve performance:
$dailySales = cache()->remember('daily_sales', 60, function () {
// Perform complex calculation on sales data
return Order::whereDate('created_at', today())->sum('total');
});
This example retrieves the sum of daily sales and stores it in the cache for 60 minutes. Subsequent requests for the same data will use the cached value, avoiding the need for recalculation.
Examples
Caching User Permissions:
Checking user permissions can involve complex logic and database queries. Caching user permissions upon login can significantly improve performance:
public function handle($request)
{
$user = $request->user();
$permissions = cache()->remember('user_permissions-' . $user->id, 60, function () use ($user) {
return $user->permissions()->pluck('name');
});
// Use $permissions for authorization checks within the controller
}
This code snippet caches the user's permissions associated with their ID for 60 minutes. Subsequent requests within the same session can access the cached permissions instead of querying the database again.
Caching Product Categories
Cache a list of product categories and their associated subcategories. This information is unlikely to change frequently and can significantly improve the speed of rendering product navigation menus.
$categories = cache()->remember('product_categories', 60, function () {
return Category::with('subcategories')->get();
});
Caching Popular Products
Cache data for frequently viewed or recently purchased products. This eliminates individual database queries for popular items, reducing load and improving response times.
$popularProducts = cache()->remember('popular_products', 60, function () {
return Product::where('is_popular', true)->get();
});
Caching Static Pages
Use the cache helper to pre-render and cache static pages like "About Us" or "Contact Us":
return cache()->remember('about_us', 60, function () {
return view('about-us');
});
Caching Blog Posts
Cache blog posts with comments disabled, especially for older posts with low update frequency.
$post = cache()->remember('post-' . $id, 60, function () use ($id) {
return Post::without('comments')->find($id);
});
Caching Trending Topics
Cache trending topics and discussions, refreshing the cache periodically to maintain updated data.
$trendingTopics = cache()->remember('trending_topics', 60, function () {
return Post::where('is_trending', true)->latest()->limit(10)->get();
});
Resources
Laravel cache
A Comprehensive Guide to Integrating Laravel Cache in Your Web Application
A Comprehensive Guide to Caching in Laravel: Boosting Application Performance
Top comments (0)