How to use Cache In Laravel Query – Larachamp
Tags: laravel, programming, coding
Published: 2022-08-21 04:57:07

---
title: How to use Cache In Laravel Query – Larachamp
published: true
date: 2022-08-15 09:17:19 UTC
tags: Laravel,Programming,Coding
canonical_url: https://larachamp.com/how-to-use-cache-in-laravel-query/
---

![what Is Cache In Laravel](https://larachamp.com/wp-content/uploads/2022/08/laravel-middleware-3-1-1024x576.png)
_cache In laravel_

Hello devs, Today we are going to learn about Cache in Laravel and I’ll also be discussing how you can use Cache while making a query to the database. Usually, I would say cache is my favorite topic because it helps on the very main point when it comes to speeding up your query result on the browser.

Each time while executing Queries and performing tasks, It takes seconds or microseconds to return the result. But when It comes to caching the result, It helps to retrieve the result quickly.

## What Is Cache In Laravel

The Cache is something that we use to store data for a particular time and also it can be forever. We use Cache in Laravel so that we can access the result faster as much as possible. It saves data from the server (when we do use cache). We don’t need to make requests for the same data on the server and also don’t need to wait for seconds to get the result.

## Why We Use Cache In Laravel

This is the main question that everyone should ask who is new to using cache. Why do we need to use cache? and the answer is simple. Cache stores all the data locally and it helps to improve loading speed and efficiency. When users do visit any site which loads data very slow, the simple solution is there you can use cache and it will pre-download all the data and later it will retrieve it from local storage which improves user experience.

## Cache Configuration In Laravel

You can find the cache file in your config directory `config/cache.php`. Laravel provides different types of cache drivers and you can use any of them as your cache driver.

Laravel supports popular caching backends like [Memcached](https://memcached.org/), [Redis](https://redis.io/), [DynamoDB](https://aws.amazon.com/dynamodb), etc.

You will have a detailed overview of the drivers in the <mark style="background-color:rgba(0, 0, 0, 0)"><code>cache.php</code></mark>. The default, stores Cache in the file. That you find under your storage directory. <mark style="background-color:rgba(0, 0, 0, 0)"><code>storage\framework\cache\data</code></mark>.

## Let’s Use Cache 

Let’s see how we can use Cache in Laravel with some practical examples.

### Store Item In The Cache

You can easily store any item in the Cache having said that you have to use Cache Facade at the top of your file.

```
Cache::put('key', 'value', $seconds = 10);
```

if we would not pass any specific time in the <mark style="background-color:rgba(0, 0, 0, 0)"><code>put</code></mark> method then the cache will store for an indefinite time.

### Store Item and Check if not exist

```
Cache::add('key', 'value', $seconds);

//add method will do this, If the item will be stored then it will return true otherwise false
```

If you do want to store the item forever then you can use the forever method for this thing.

```
Cache::forever('key', 'value');
```

### Remove Items from Cache

You can remove items from the Cache by using the <mark style="background-color:rgba(0, 0, 0, 0)"><code><em>forget</em></code></mark> method.

```
Cache::forget('key');
// here you have to pass the key, which you want to remove.
```

If you want to remove the cache for all items then you can use the <mark style="background-color:rgba(0, 0, 0, 0)"><code><em>flush</em></code></mark>() method.

```
Cache::flush();.
```

## Tags Cache In Laravel

Cache tags don’t work with all drivers, It only works with  [Memcached](https://memcached.org/) so, I would prefer If you do want to know about it you can read it on the [official documentation](https://laravel.com/docs/8.x/cache#cache-tags).

## Practical Example Of Using Cache In Laravel Query Result

We have a user table and we want to fetch all the users. We will write a query to fetch the users and then we will get all the users through Cache and then If we will hit the request again to get the users list then we will check if we would have that data cached or not.

This is how this process will work. Let’s see the example. And If you will have any query let me know in the comment box.

I am into my controller and I’ll have the show function which will do all the tasks.

```
 public function show()
    {
        $parentId = Auth::User()->id;
        $ClientsData = Cache::remember('clients', 60 * 60, function () use ($parentId) {
            return User::where('parent_id', $parentId)->orderByDesc('id')->with('file')->get();
        });
        return view('usersListing', ['clients' => $ClientsData]);
    }
```

Let’s understand the process of function.

When we use the <mark style="background-color:rgba(0, 0, 0, 0)"><code>Cache::remember</code></mark> function that means we are checking if <mark style="background-color:rgba(0, 0, 0, 0)"><code>clients</code></mark> the named cache exists or not. If not then fetch from the database.

If you are using CRUD operation with the listing then don’t forget to use the Observer to forget the Cache. The below video will help you to understand it more deeply.

<iframe loading="lazy" title="Eloquent Observers or Events Listeners? Which is Better?" width="640" height="480" src="https://www.youtube.com/embed/DvoaU6cQQHM?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

_Learn about Observers_

Thanks For Watching and Reading. I hope It will help you somewhere in your developer journey. Look at [Laravel Tips](https://larachamp.com/category/laravel/laravel-tips/) Page, Maybe you will find something useful.

The post [How to use Cache In Laravel Query – Larachamp](https://larachamp.com/how-to-use-cache-in-laravel-query/) first appeared on [larachamp.com](https://larachamp.com).

The post [How to use Cache In Laravel Query – Larachamp](https://larachamp.com/how-to-use-cache-in-laravel-query/) appeared first on [larachamp.com](https://larachamp.com).