Posts Learn Components new Snippets new 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

31 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.
new

If you like our tutorial, do make sure to support us with some coffee. We need the juice to write the content during the night 🤙🏻