Redis is an open source (BSD licensed), in-memory data structure store, used as a database, cache and message broker.

Before using Redis, we need to install and start redis server.

Redis official site.
For windows visit: Install redis on windows.

To use redis with Laravel, you will first need to install the predis/predis.

composer require predis/predis

Configure redis with laravel:
In you database configuration file located in config/database.php

'redis' => [
    'cluster' => false,

    'default' => [
        'host'     => env('REDIS_HOST', 'localhost'),
        'password' => env('REDIS_PASSWORD', null),
        'port'     => env('REDIS_PORT', 6379),
        'database' => 0,
    ],
]

After redis has been configured, we can use redis cache command in controller to render the view page and cache the output in redis and retrieve it for next call. Assuming we want to cache home page, returned using index function.

public function index()
{
    //Retrive cache data from redis.
    $page = Cache::tags('site_cache')->get('home');

    //Check if cache exits, if not add cache to redis or return cache data from redis server.
    if ($page != null && $page!='') {
        return $page;
    }
    else{
        Cache::tags('site_cache')->put('home', $this->getHome()->render().'', 1);
    }
    return view('home');
}

Note: Since all request to home page are returned from redis cache. Any changed to the home page won't be seen in the call request. Hence we can clear the cache whenever any changes occurs in the actual webpage.

Example function to clear Laravel cache in redis.

public function clearViewCache()
{
    $keys = Redis::keys('laravel:*');
    foreach ($keys as $key)
    {
        Redis::del($key);
    }
    return \Redirect::back()->withFlashMessage('All view clear has been cleared!');
}

Related

PHP

Custom form request for Google Recaptcha.

PHP

Increase site speed using Redis as a caching server.

PHP

This article will cover how to deploy a Laravel project in shared hosting.

PHP

Tagging is a popular way of categorizing posts in any blog or news related sites.

keyboard_arrow_up