Read Story
Avail Here
Visit Here
Ayush Bhatt

How to use Redis with Laravel ?

What is Redis ?

Redis is an open source (BSD licensed). It is used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams. It is an open source, advanced key-value store.

Redis is written in ANSI C and works in most POSIX systems like Linux, *BSD, OS X without external dependencies. Linux and OS X are the two operating systems where Redis is developed and tested the most, and we recommend using Linux for deploying. Redis may work in Solaris-derived systems like SmartOS, but the support is best effort. There is no official support for Windows builds.

Redis in Laravel

In order to use Redis with Laravel, firstly yo will have to install the predis/predis package.
You can install it via composer.

Just run this command and you’re done.

Apart from this, you can also install php redis, a php extension via PECL. This package is comparatively complex to install so it is better to use predis package via composer.

Configuration of Redis for Laravel Application

The Redis configuration for laravel application is present in the config/database.php.
In this file you can see the redis array which contains the Redis servers utilized by laravel application:

You can modify this array based on your environment. Each Redis server defined in your configuration file is required to have a name, host, and port.

Now how to interact with Redis ?

You will have to use a Redis facade for this.

The Redis facade supports dynamic methods, meaning you may call any Redis command on the facade and the command will be passed directly to Redis. In this example, we will call the Redis GET command by calling the get method on the Redis facade:

You may call any of the Redis commands on the Redis facade. Laravel uses magic methods to pass the commands to the Redis server, so pass the arguments the Redis command expects:

Apart from this, you can also pass your commands to the server with the help of command() method.
It accepts the name of the command as its first argument, and an array of values as its second argument:

Pipelining

Pipelining is a concept through which one can  send many commands to the server in one operation. The pipeline method accepts one argument: a Closure that receives a Redis instance. You may issue all of your commands to this Redis instance and they will all be executed within a single operation:

Source:
Laravel
Redis

. . .

Comment

Add Your Comment

Be the first to comment.

css.php