Posts Learn Components Snippets Categories Tags Tools About

Caching Queries and Values in Laravel 8

Learn how to enhance your application speed and performance in Laravel by caching the queries result.

Created on Jun 27, 2021


One of the ways to improve your website performance is by caching the query result. To achieve this you have to make use of the "cache" helper and call on the "remember" method.

Imagine your application kept on performing a query on the user table like below. If you are not caching the data then the load will be high.
$users = User::get(['id', 'name', 'email']);

So to cache the data you can wrap the code above like this.
$users = cache()->remember('users', 300, function () {
    return User::get(['id', 'name', 'email']);

We specify the cache key to be "users" and set the cache time to 300 seconds. On subsequent requests if there's data stored in the cache then it's returned otherwise a new cache is created and the data is returned to the user.

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for Caching Queries and Values in Laravel 8