Laravel Cloud is here! Zero-config managed infrastructure for Laravel apps. Deploy now.

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
Jump24 - UK Laravel Agency

Laravel Developers that Click into Place. Never outsourced. Never offshored. Always exceptional.

Visit Jump24 - UK Laravel Agency
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $3200/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
Tinkerwell logo

Tinkerwell

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

Tinkerwell
Get expert guidance in a few days with a Laravel code review logo

Get expert guidance in a few days with a Laravel code review

Expert code review! Get clear, practical feedback from two Laravel devs with 10+ years of experience helping teams build better apps.

Get expert guidance in a few days with a Laravel code review
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
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
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
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

The latest

View all →
Laravel Cloud Adds “Markdown for Agents” to Serve AI-Friendly Content image

Laravel Cloud Adds “Markdown for Agents” to Serve AI-Friendly Content

Read article
Laravel Releases Nightwatch MCP Server for Claude Code and AI Agents image

Laravel Releases Nightwatch MCP Server for Claude Code and AI Agents

Read article
Single Table Inheritance for Eloquent Models Using Parental image

Single Table Inheritance for Eloquent Models Using Parental

Read article
Laravel Live Denmark Returns to Copenhagen in August 2026 image

Laravel Live Denmark Returns to Copenhagen in August 2026

Read article
Generate Secure, Memorable Passphrases in PHP with PHP Passphrase image

Generate Secure, Memorable Passphrases in PHP with PHP Passphrase

Read article
FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches image

FrankenPHP v1.11.2 Released With 30% Faster CGO, 40% Faster GC, and Security Patches

Read article