Home / Snippets / Caching Queries and Values in Laravel 8
Caching Queries and Values in Laravel 8 cover

Caching Queries and Values in Laravel 8

179

3 years ago

0 comments

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.
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

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

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this