DEV Community

Sonika Baniya
Sonika Baniya

Posted on • Originally published at techradiant.com

Laravel Caching

In basic understanding, Caching makes things faster. If I ask you the computation of 4x5 then your immediate answer would be 20. Your brain has done this computation several times that it doesn’t even need to be done again. Imagine if you had to do it by drawing four lines repeating five times and count it like you did it for the first time in our childhood. Then it would be a very expensive process(in terms of processing and time). Exactly the same case.

Laravel provides API for various caching mechanisms. Cache configuration is located at config/cache.php in your laravel project. Laravel supports famous caching backends like Memcached, Redis. It looks something like:

Alt Text

Cache Usage

We can access Laravel cache in two ways i.e Factory and Repository. The factory provides access to all cache drivers defined. The repository is an implementation of the default cache driver for your application as specified by a cache configuration file. But on top of that, we use cache by cache facade as the best implementation of Factory and Repository as

Illuminate\Support\Facades\Cache
Enter fullscreen mode Exit fullscreen mode

Cache methods

put():

This method takes three parameters i.e key, value and time in minutes.

Cache::put('cachekey', 'I am the cache',10);
Enter fullscreen mode Exit fullscreen mode

get():

This method either takes one or two parameters i.e key and value after the cache is expired.

Cache::get('cachekey); 
Cache::get('cachekey', 'Cache died, so heres aftercache data');
Enter fullscreen mode Exit fullscreen mode

has():

It returns a boolean value and takes a key as a parameter.

if(Cache::has('cachekey')){
     return true;
}
Enter fullscreen mode Exit fullscreen mode

forever():

This method is useful when you want data to be available for user irrelevant of time. And it takes key and value as a parameter.

Cache::forever( 'cachekey', 'I am in the forever cache data!' );
Enter fullscreen mode Exit fullscreen mode

forget():

This method is useful if you have used forever() method previously or you need to expire cache before the allocated time.

Cache::forget('cachekey');
Enter fullscreen mode Exit fullscreen mode

Also, database caching and route caching can come into great handy.

Response time with and without cache

Let us take a simple example of accessing the Students model which stores the information of 40 students of a classroom.

Without any caching mechanism, simple PHP code to access it would be:

public function index() {
    $students = Students::all();
    return response()->json($students);
}
Enter fullscreen mode Exit fullscreen mode

With the caching mechanism, it would be something like:

public function index() {
    $students = Cache::remember('students', 24*60, function() {
        return Students::all();
    });
    return response()->json($students);
}
Enter fullscreen mode Exit fullscreen mode

Now, let’s take a look at response time in its 1st, 2nd, 3rd and 4th hit respectively.

Alt Text

The first hit takes a longer time because computationally, it is storing data in cache + retrieving data for end-user. But after the first hit, response time is much less. So, for the larger application Memcached, Redis driver is much recommended.

Atomic Lock

Atomic Lock means one server being used by one process at one time to avoid a race condition. The race condition is an undesirable condition which occurs when two task/process tries to access the same resource but due to the system’s nature needs to be done sequentially.

Cache::lock('key',10);
Enter fullscreen mode Exit fullscreen mode

Cache Helper

If you reflect back from the start of this article to till now then you know one thing for sure i.e cache can be accessed from cache facade. In addition to that, the cache can also be accessed from cache global function.

cache(['key' => 'value'], $seconds);
Enter fullscreen mode Exit fullscreen mode

Happy reading!

This article was originally published on https://www.techradiant.com/2020/02/20/laravel-caching/

Top comments (1)

Collapse
 
bangbangda profile image
24Kdabaiyang

The third parameter of the Cache::put method, the expiration time should be in seconds. is not minutes.