Utilizing Laravel’s Cache with Query Params
Laravel Tutorials / April 04, 2017

Utilizing Laravel’s Cache with Query Params

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;
});

Laravel News Partners

Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.