Utilizing Laravel’s Cache with Query Params

Published on by

Utilizing Laravel’s Cache with Query Params image

Laravel provides a very intuitive and useful means of caching the responses of your projects, whatever your project is (RESTful API, Web Platform, etc.). In general, Laravel can store in the cache system whatever data you send (HTML, JSON, collections, Eloquent instances, and similar) accordingly with a provided expiration time.

Going straight with the code, a snippet for caching a simple response can be this:

return Cache::remember($rememberKey, $minutes , function() use ($data) {
return $data;
});

The code looks very simple, and it is. You call the remember token to obtain cached data and store it in the cache whenever it does not exists, send a $rememberKey to identify the data in the cache system, and the expiration time (in minutes). Using a Closure, you can return the data to store in the cache system. It’s so simple the developer may not realize all the power in a single line. Let’s go one by one with the most relevant elements here.

There exist several methods to use with cache like PUT, PULL, GET, and so on (details about all of them here), but the remember method is all you need because it stores and retrieves the data for you.

The question here is “How does Laravel determine when to store data?

To answer this, we need to go with another essential element, the “rememberKey.” Depending on the value of the $rememberKey, Laravel will know if this data was cached already or not. So here is the importance of this value because if you use the same $rememberKey to cache all your responses you are going to obtain the same response along the expiration time, it seems obvious no?

Unfortunately, it is not very obvious for other scenarios. As you are aware of the importance of a unique value for the $rememberKey you decide to use the current URL, so the code goes like this:

$url = request()->url();
return Cache::remember($url, $minutes, function () use ($data) {
return $data;
});

Almost the same, but now the $rememberKey is the URL of the current request, in that way you are going to be sure the remember key is going to be different depending on the request.

For example, if you receive a request to yourdomain.com/products this is going to cache the response with that exact value. Whenever the user goes to another URL, like yourdomain.com/categories, you need to be sure the cache system is going to return the corresponding values and store it accordingly.

But, wait a minute! Let’s imagine you are using query parameter to sort or paginate the results, so your URL looks like this: yourdomain.com/products?page=2&sort_by=price. In that case, when you obtain the URL issuing $url = request()->url() it does not obtain the query parameters, and that means the changes in the response introduced by the query parameters are not going to be reflected.

No problem, you just need to include the query parameters and everything is going to be fine, right? Let’s do it.

$fullUrl = request()->fullUrl();
return Cache::remember($fullUrl, $minutes, function () use ($data) {
return $data;
});

Ok, it’s done! Or not? Hold your horses a little. Let’s do some testing. If the user sends a request to yourdomain.com/products?page=2&sort_by=price it is going to cache the data and return the response. If the user sends a request to yourdomain.com/products?page=1&sort_by=name, it is going to cache the data again and return. Excellent! It is caching different responses and returning them. Now, for the last test. The user visits yourdomain.com/products?page=2&sort_by=price and then visit yourdomain.com/products?sort_by=price&page=2. It’s a different request, so the cache system is going to cache everything independently, good! Oh, wait a minute! This is the same response. It doesn’t matter the order in the query string, your project is going to return the same response and if it is the same response the cache system should store it, but it doesn’t!

Oh man, what can I do now? It looks like the solution is not as simple as we believe in the beginning. We need a way to be sure, independently of the order of the query string, whenever it is the same we do not want to cache the data again. We need to sort the query string.

Let’s do it in code:

$url = request()->url();
$queryParams = request()->query();
 
//Sorting query params by key (acts by reference)
ksort($queryParams);
 
//Transforming the query array to query string
$queryString = http_build_query($queryParams);
 
$fullUrl = "{$url}?{$queryString}";
 
return Cache::remember($fullUrl, $minutes, function () use ($data) {
return $data;
});

Where is the magic here? Well, we just get the query parameters on an associative array using the query method and then sort it using the keys (not the values), using ksort. The ksort function acts by reference, so we do not need to assign again. Then with the query parameters sorted we can build the query string again, using the http_build_query to finally build the fullUrl in the right way to use it as the remember key.

After this, if the user goes to yourdomain.com/products?sort_by=price&page=2 it is going to be the same as yourdomain.com/products?page=2&sort_by=price allowing you to cache the same response, even when the URL on the request looks a little different.

If you want a “fancy” solution, you can even hash the fullurl, something like this:

$url = request()->url();
$queryParams = request()->query();
 
ksort($queryParams);
 
$queryString = http_build_query($queryParams);
 
$fullUrl = "{$url}?{$queryString}";
 
$rememberKey = sha1($fullUrl);
 
return Cache::remember($rememberKey, $minutes, function () use ($data) {
return $data;
});
JuanDMeGon photo

Online instructor (Spanish and English). Web development lover, #Laravel lover, and @ProgramarYA owner.

Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Version 4 of Tinkerwell is available now. Get the most popular PHP scratchpad with all its new features and simplify your development workflow today.

Visit Tinkerwell
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
Bacancy - Staff Augmentation logo

Bacancy - Staff Augmentation

Leave your web app development hustles to the leading IT Staff Augmentation Service Providers. Choose from an extensive pool of 1050+ developers and give yourself the sigh of success you deserve with Bacancy. Get In Touch Today!

Bacancy - Staff Augmentation
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
October CMS v3.6 Ships Today, Full of New Features image

October CMS v3.6 Ships Today, Full of New Features

Read article
Laracon EU Videos are now out image

Laracon EU Videos are now out

Read article
Use Google's Gemini AI in Laravel image

Use Google's Gemini AI in Laravel

Read article
PhpStorm is getting a brand new terminal image

PhpStorm is getting a brand new terminal

Read article
Six Essential Plugins for Visual Studio Code image

Six Essential Plugins for Visual Studio Code

Read article
Modularize Your Laravel Application With the Modular Package image

Modularize Your Laravel Application With the Modular Package

Read article