Caching Complex Queries in Laravel for Improved Performance

In the world of web applications, performance is key. Sometimes, we run into situations where our queries are too complex and take a significant amount of time to return results. In such cases, if we know that the response remains the same for a long duration and doesn’t change based on certain conditions, hitting the server repeatedly for the same response is inefficient. This is where caching can come to the rescue.

In this example, I will explore how to use Laravel’s caching system to store the results of complex queries, particularly when we are certain that the results will remain the same for a few hours based on certain conditions.

Problem
Imagine you have a query that is based on a condition array. If the condition array contains the same values, the result for that condition is not going to change for the next 3-4 hours. The query itself is quite complex and takes seconds to execute – time that adds up with each request, thereby slowing down your application. It happens to me and i solved it with Laravel caching.

The Solution: Caching in Laravel

Laravel provides an elegant and straightforward caching system. We can use this system to store the results of our complex query and serve this cached data instead of re-running the query for each request. Here’s how we can do it:

  1. Generate a Unique Cache Key: Based on the input condition array, we generate a unique cache key.
  2. Check if the Data is Already in the Cache: Before running the query, we check if the data is already in the cache using this unique key.
  3. Retrieve the Data from Cache or Run the Query: If the data is in the cache, we return it. If not, we run the query, store the result in the cache, and then return it.

Code before implementation:

public function getDemoGraphicDataFields(Array $companyArray){
        $finalFilter = [
            'meta_keys',
            'meta_value'
        ];
        $demographicFilter = UserInfo::when($companyArray, function($query,$companyArray){
            $query->whereIn('company_id', $companyArray);
        })
        ->distinct()
        ->pluck('meta_key');
        $finalFilter = [];
        foreach ($demographicFilter as $key => $value){
            
            $demographicValueFilter = UserInfo::when($companyArray, function($query,$companyArray){
                $query->where('company_id', $companyArray);
            })->where('meta_key',$value)
            ->distinct()
            ->pluck('meta_value');
            $finalFilter['meta_values'][$value] = $demographicValueFilter;
        }
        $finalFilter['meta_keys'] = $demographicFilter;
        return $finalFilter;
        
    }

code after laravel caching implementation: 

use Illuminate\Support\Facades\Cache; //add this in top of your controller file

public function getDemoGraphicDataFields(Array $companyArray)
{
    // Generate a unique cache key based on the company array
    $cacheKey = 'demographic_data_fields:' . md5(serialize($companyArray));

    // Try to get the data from the cache
    $finalFilter = Cache::get($cacheKey);

    // If the data is not in the cache, run the query
    if ($finalFilter === null) {
        $demographicFilter = UserInfo::when($companyArray, function($query, $companyArray){
            $query->whereIn('company_id', $companyArray);
        })
        ->distinct()
        ->pluck('meta_key');

        $finalFilter = [];
        foreach ($demographicFilter as $key => $value) {
            $demographicValueFilter = UserInfo::when($companyArray, function($query, $companyArray){
                $query->whereIn('company_id', $companyArray);
            })->where('meta_key', $value)
            ->distinct()
            ->pluck('meta_value');
            
            $finalFilter['meta_values'][$value] = $demographicValueFilter;
        }
        
        $finalFilter['meta_keys'] = $demographicFilter;

        // Store the result in the cache for 3 hours (180 minutes)
        Cache::put($cacheKey, $finalFilter, 180);
    }

    // Return the data (either from the cache or from the query)
    return $finalFilter;
}

 

Remarkable Improvement: After implementing this caching strategy, the response time of my application dramatically dropped from 10 seconds to a mere 500 milliseconds. That’s a 20-fold increase in speed, showcasing the incredible efficiency that caching can bring to your application’s performance.

Key Takeaways

  • Caching is a powerful solution for optimizing the performance of your application.
  • In scenarios where the response remains constant for a long duration, caching that response saves server resources.
  • Laravel provides an easy and elegant way to implement caching, allowing you to decide when and how to store, retrieve, and invalidate cache data.

Complex queries can be resource-intensive and slow down your application, especially when they are executed frequently. By utilizing Laravel’s caching system, you can dramatically improve the performance of your application, reduce server load, and enhance the user experience.

#laravel #laravelcaching #laravelmysql #laravelmysqlcaching #laravelcaching

 

Don’t miss these tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

By CLTK

Leave a Reply

Your email address will not be published. Required fields are marked *