Cachebusters
Tags: laravel, cache, performance, php
Published: 2020-05-06 21:31:22

**Let's talk about cache baby!** In this post, you will get all information about caching methods and patterns which match with your laravel app. Caching is a great aspect. Deal with it and implement it now.

> I will also add all sources, interesting links, and videos so you can learn much more about the magic of caching in laravel.

![running fast](https://media.giphy.com/media/l2Sqc3POpzkj5r8SQ/giphy.gif)

## At first I will ask some question?

How many files are required for one request in laravel?

> Roundabout 218 files. I've found that answer in some older presentation, https://www.slideshare.net/chtalbert/the-integration-of-laravel-with-swoole

That is huge stuff to answer only one request. I know the answer is not so easy, it depends on your used laravel version and the setup, but the answer is enough to get a feeling! Don't waste the time of your visitors, save them. They are searching for information. Bring up your information fast, nobody wants to wait.

##You have also no time?
Then take some short way. Drink a coffee and implement the laravel coffee cache.

{% github linslin/laravel-coffee-cache %}

link: ☕ https://github.com/linslin/laravel-coffee-cache

If you have time and you will digging deeper than the next explanations are for you.

# the request
>The beginning of each good journey starts with some https ... request!

Someone on this globe is visiting your page (hopefully built with laravel), then boom over 200 files are called to pass the framework and answer the request.

The request passed by routes, logic, views, controllers & all the magic inside your laravel app.

At the end of **each** request, all is passed but required to answer only one simple user request. All that "magic" steps take time. The request journey is called the "lifecycle".

>Time is like a ghost and now you will learn how you can cache them. Be an cachebuster. **Don't repeat** the same queries on **each** request, you know don't repeat yourself **use cache instead**.

## lifecycle

For understanding a request it is every time a great idea if you are looking for some diagrams or explanations "laravel lifecycle" is a great keyword. Here some short compressed overview.

> If you are searching for laravel lifecycle or take a breath of the fantastic documentation you can find more concrete stuff: https://laravel.com/docs/7.x/lifecycle

### The short way (laravel request lifecycle):

It is an MVC-Framework.

1) Your laravel app got some user requests.
2) Over public/index.php & the web.php, the route is called.
3) The route calls the controller, he is acting with models (database) & data (files).
4) All collected data are passed to the view.

That is the short explanation.
Now the longer one:

### The detailed perspective

1) Request
2) public/index.php
3) Autoload
4) Load App
5) Http Kernel
6) Bootstrap
7) Register Service Providers
8) Boot Service Providers
9) Middleware
10) Dispatch by router
11) Routes Match
12) Controller
13) Response
14) Terminate middleware

![livecycle](https://i.imgur.com/549sDDI.png)
> https://blog.albert-chen.com/the-integration-of-laravel-with-swoole-part-1/


I think it is clear. All that stuff needs time. If you are using some caching pattern the request can answer faster, because some steps are skipped for a specified time.

> It is like you save some phone numbers in your phone. You don't need to think about all the numbers, you can call directly. The workflow is short. Or you can think vice versa if someone is calling you and you see directly her or his name.

## What is caching and why you should use it?

> Caching [...] is a software component that stores data so that future requests for that data can be served faster; the data stored in a cache might be the result of an earlier computation or a copy of data stored elsewhere. A cache hit occurs when the requested data can be found in a cache, while a cache miss occurs when it cannot. **Cache hits are served by reading data from the cache, which is faster than recomputing a result** or reading from a slower data store; **thus, the more requests that can be served from the cache, the faster the system performs.**, https://en.wikipedia.org/wiki/Cache_(computing)

* SpeedUp your page (from 472ms to 284ms) ...
* Reduce the load 
* Fewer queries
* faster results

The target is to get most data directly from cache instead of databases.

## caching behavior

At first there exist different caching ideas & patterns.
You can cache the whole rendered output (the whole dom of your page) or you can decide to cache only database queries or you activate the route cache.

Then you can also decide where you want to save your cache.

I will show you all possibilities.

Let's start with

#Cache Routing
Route Caching exist since laravel 5.
Route caching just caches the translation of incoming requests to controller action not the actual data or response from the controller.

Artisan commands enter in your CLI:

```php
// creates a serialized result of your route.php
php artisan route:cache

// clear the route cache file, use it if you have changed routes.php
php artisan route:clear
```

Quicknote:
The artisan route:cache command serializes the results of the route.php
Routes are parsed from the cached file, not the routes file.

Read more here: https://mattstauffer.com/blog/laravel-5.0-route-caching/

#Caching eloquent queries

## Cache driver(s)

```php
// Take a look at .env
CACHE_DRIVER=file
```

Also, possible cache_drivers are: Memcached, Redis, Database, File, Array

```php

/* 
use this to put something into your cache
key = you should set some unique name to identify,
if you have multiple apps that write in your cache storage use also prefixes.

value = the cached, use closures to put for example eloquent stuff in the cache

duration = how long the cache should stay, 
the unit depends on laravel version (ms, s)

*/
Cache::put('someUniqueKey', 'value', 60); 

// here with remember & closure

Cache::remember('allPosts', 60, function() {
    return Posts::all();
});

// read the cache by key

Cache::get('allPosts');

// check and read from cache or put

if (Cache::has('allPosts')){
    Cache::get('allPosts');
} else {
    Cache::put('allPosts', $cachedStuff, 60);
}

// forget all cached stuff by key

Cache::forget('allPosts');

```
or clear the cache via CLI

```php
php artisan cache:clear
```

#Timing comparisons

Some interesting article about caching & timing Memcache vs Redis.

https://scotch.io/tutorials/caching-in-laravel-with-speed-comparisons#toc-results-recommendation

#Testing

You can use for example the postman browser extension to test and track your caching mechanism and timing.

#Learn more / code more / read more

{% link https://dev.to/larashout/laravel-clear-cache-using-artisan-command-4f6m %}

#Videos

learn how to set up and use config cache

{% youtube LA2jgtAn4Sc %}

cache eloquent queries

{% youtube JhKngeE0XJA %}

cache with Redis

{% youtube zCMypIqZQzo %}

cache how to measure the duration

{% youtube bQBNAPN0iU0 %}

Sources and links which help to learn more:

https://www.google.com/amp/s/www.cloudways.com/blog/integrate-laravel-cache/amp/
https://www.slideshare.net/chtalbert/the-integration-of-laravel-with-swoole
https://laravel.com/docs/4.2/cache
https://mattstauffer.com/blog/laravel-5.0-route-caching/
https://medium.com/swlh/cache-eloquent-queries-in-laravel-6-af722c09a6f7
https://www.mindtwo.de/blog/laravel-cache-bessere-web-performance
https://vegibit.com/laravel-cache-tutorial/
https://scotch.io/tutorials/caching-in-laravel-with-speed-comparisons
https://laravel-news.com/page-cache
https://stackoverflow.com/questions/59073842/laravel-how-to-cache-route-for-5-minutes
https://stackoverflow.com/questions/59073842/laravel-how-to-cache-route-for-5-minutes#comment104385474_59073842
https://docs.spatie.be/laravel-permission/v3/advanced-usage/cache/
https://voltagead.com/practical-object-caching-in-laravel/
https://freek.dev/1351-caching-the-entire-response-of-a-laravel-app
https://blog.albert-chen.com/the-integration-of-laravel-with-swoole-part-1/