DEV Community

Cover image for Laravel Caching
Mike Varenek
Mike Varenek

Posted on

Laravel Caching

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();
});

Enter fullscreen mode Exit fullscreen mode

Rendered Views:

Laravel allows you to cache the output of views, which can be beneficial for frequently accessed pages. You can use the cachemethod in your routes or controllers to cache the rendered views:

return cache()->remember('my.view', $minutes, function () {
    return view('my.view');
});

Enter fullscreen mode Exit fullscreen mode

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');

Enter fullscreen mode Exit fullscreen mode

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');
});

Enter fullscreen mode Exit fullscreen mode

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
}

Enter fullscreen mode Exit fullscreen mode

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();
});

Enter fullscreen mode Exit fullscreen mode

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();
});

Enter fullscreen mode Exit fullscreen mode

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');
});

Enter fullscreen mode Exit fullscreen mode

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);
});

Enter fullscreen mode Exit fullscreen mode

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();
});

Enter fullscreen mode Exit fullscreen mode

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)