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.

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
Laravel Idea for PhpStorm logo

Laravel Idea for PhpStorm

Ultimate PhpStorm plugin for Laravel developers, delivering lightning-fast code completion, intelligent navigation, and powerful generation tools to supercharge productivity.

Laravel Idea for PhpStorm
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
Bacancy logo

Bacancy

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

Bacancy
Lucky Media logo

Lucky Media

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

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
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
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
Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate logo

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate

Build your SaaS application in hours. Out-of-the-box multi-tenancy and seamless Stripe integration. Supports subscriptions and one-time purchases, allowing you to focus on building and creating without repetitive setup tasks.

Supercharge Your SaaS Development with FilamentFlow: The Ultimate Laravel Filament Boilerplate
JetShip - Laravel Starter Kit logo

JetShip - Laravel Starter Kit

A Laravel SaaS Boilerplate and a starter kit built on the TALL stack. It includes authentication, payments, admin panels, and more. Launch scalable apps fast with clean code, seamless deployment, and custom branding.

JetShip - Laravel Starter Kit
Rector logo

Rector

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

Rector
MongoDB logo

MongoDB

Enhance your PHP applications with the powerful integration of MongoDB and Laravel, empowering developers to build applications with ease and efficiency. Support transactional, search, analytics and mobile use cases while using the familiar Eloquent APIs. Discover how MongoDB's flexible, modern database can transform your Laravel applications.

MongoDB

The latest

View all →
Streamlining Route Parameters in Laravel Using URL Defaults image

Streamlining Route Parameters in Laravel Using URL Defaults

Read article
Flexible Docker Images with PHP INI Environment Variables image

Flexible Docker Images with PHP INI Environment Variables

Read article
Dynamic Form Validation in Laravel with prohibited_if image

Dynamic Form Validation in Laravel with prohibited_if

Read article
Add Approvals to Your Laravel Application image

Add Approvals to Your Laravel Application

Read article
Enhancing Data Processing with Laravel's transform() Method image

Enhancing Data Processing with Laravel's transform() Method

Read article
Get Xdebug Working With Docker and PHP 8.4 in One Minute image

Get Xdebug Working With Docker and PHP 8.4 in One Minute

Read article