Posts Learn Snippets Categories Tags 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

17 views

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.

Created by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.