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
SerpApi

The Web Search API for Your LLM and AI Applications

Visit SerpApi
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 $9500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Laravel Cloud logo

Laravel Cloud

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

Laravel Cloud
Harpoon: Next generation time tracking and invoicing logo

Harpoon: Next generation time tracking and invoicing

The next generation time-tracking and billing software that helps your agency plan and forecast a profitable future.

Harpoon: Next generation time tracking and invoicing
Lucky Media logo

Lucky Media

Get Lucky Now - the ideal choice for Laravel Development, with over a decade of experience!

Lucky Media
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Shift logo

Shift

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

Shift
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Multi-tenant Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Acquaint Softtech logo

Acquaint Softtech

Acquaint Softtech offers AI-ready Laravel developers who onboard in 48 hours at $3000/Month with no lengthy sales process and a 100 percent money-back guarantee.

Acquaint Softtech
PhpStorm logo

PhpStorm

The go-to PHP IDE with extensive out-of-the-box support for Laravel and its ecosystem.

PhpStorm

The latest

View all →
In-Memory Eloquent Models with Truffle image

In-Memory Eloquent Models with Truffle

Read article
Detect and Resolve Laravel Schema Drift with MigrAlign image

Detect and Resolve Laravel Schema Drift with MigrAlign

Read article
Laravel Cloud Adds Scale-to-Zero and Spending Limits image

Laravel Cloud Adds Scale-to-Zero and Spending Limits

Read article
Shift + AI = Fully Automated Laravel Upgrades image

Shift + AI = Fully Automated Laravel Upgrades

Read article
Laracon AU 2026 Announces Full Speaker Lineup, Schedule, and Workshops image

Laracon AU 2026 Announces Full Speaker Lineup, Schedule, and Workshops

Read article
Parsel: Parse PDFs, Office Documents, and Images in PHP image

Parsel: Parse PDFs, Office Documents, and Images in PHP

Read article