We’ve all seen many websites that were so slow, making us crazy not being fast enough, and we ended up leaving them and not coming back to them anymore.

Imagine having a website with a lot of requests to your database sooner or later you will have to dedicate a lot of computing power for responding DB requests, and you will have to pay tons of money for it.

So is there any way to lessen the DB queries while having the same number of requests?

Yes, **caching **can help with this issue.

If you’re using the Laravel framework as your backend stack for your website/web application, this is quite easy to configure. Laravel has some drivers ready out of the box, some of them are:

  1. File
  2. Redis
  3. Memcached

File driver is a good choice, but if you want to do something on a bigger scale, and much faster, you should probably use Redis or Memcached.

In this article, we will see how does caching work with Redis in 2 simple steps:

I assume you have both Laravel and Redis up and running on your local environment.

  1. Add Redis configurations, and set the cache driver to use Redis (in the .env file):

Image for post

.env file

As you know, Redis is an in-memory key-value database. This is how you can add a key and value pair to it:

Cache::put($key, $value, $ttl);
Cache::put('foo', 'bar', 600);

This will save ‘foo’ with the value ‘bar’ that will remain for 10 minutes (600 seconds). To get the value of the cache, we can use:

$foo = Cache::get('foo');

This is the way we retrieve posts from the database.

Image for post

#cache #laravel #php #sql-queries #database

Caching Eloquent queries with Redis in Laravel
8.20 GEEK