WARNING You're browsing the documentation for an old version of Laravel. Consider upgrading your project to Laravel 12.x .
Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can containstrings,hashes,lists,sets, andsorted sets.
Before using Redis with Laravel, you will need to install thepredis/predis package via Composer:
1composerrequirepredis/predisAlternatively, you may install thePhpRedis PHP extension via PECL. The extension is more complex to install but may yield better performance for applications that make heavy use of Redis.
The Redis configuration for your application is located in theconfig/database.php configuration file. Within this file, you will see aredis array containing the Redis servers utilized by your application:
1'redis'=> [ 2 3'client'=>'predis', 4 5'default'=> [ 6'host'=>env('REDIS_HOST','localhost'), 7'password'=>env('REDIS_PASSWORD', null), 8'port'=>env('REDIS_PORT',6379), 9'database'=>0,10 ],11 12],The default server configuration should suffice for development. However, you are free to modify this array based on your environment. Each Redis server defined in your configuration file is required to have a name, host, and port.
If your application is utilizing a cluster of Redis servers, you should define these clusters within aclusters key of your Redis configuration:
1'redis'=> [ 2 3'client'=>'predis', 4 5'clusters'=> [ 6'default'=> [ 7 [ 8'host'=>env('REDIS_HOST','localhost'), 9'password'=>env('REDIS_PASSWORD', null),10'port'=>env('REDIS_PORT',6379),11'database'=>0,12 ],13 ],14 ],15 16],By default, clusters will perform client-side sharding across your nodes, allowing you to pool nodes and create a large amount of available RAM. However, note that client-side sharding does not handle failover; therefore, is primarily suited for cached data that is available from another primary data store. If you would like to use native Redis clustering, you should specify this in theoptions key of your Redis configuration:
1'redis'=> [ 2 3'client'=>'predis', 4 5'options'=> [ 6'cluster'=>'redis', 7 ], 8 9'clusters'=> [10// ...11 ],12 13],In addition to the defaulthost,port,database, andpassword server configuration options, Predis supports additionalconnection parameters that may be defined for each of your Redis servers. To utilize these additional configuration options, add them to your Redis server configuration in theconfig/database.php configuration file:
1'default'=> [2'host'=>env('REDIS_HOST','localhost'),3'password'=>env('REDIS_PASSWORD', null),4'port'=>env('REDIS_PORT',6379),5'database'=>0,6'read_write_timeout'=>60,7], If you have the PhpRedis PHP extension installed via PECL, you will need to rename theRedis alias in yourconfig/app.php configuration file.
To utilize the PhpRedis extension, you should change theclient option of your Redis configuration tophpredis. This option is found in yourconfig/database.php configuration file:
1'redis'=> [2 3'client'=>'phpredis',4 5// Rest of Redis configuration...6],In addition to the defaulthost,port,database, andpassword server configuration options, PhpRedis supports the following additional connection parameters:persistent,prefix,read_timeout andtimeout. You may add any of these options to your Redis server configuration in theconfig/database.php configuration file:
1'default'=> [2'host'=>env('REDIS_HOST','localhost'),3'password'=>env('REDIS_PASSWORD', null),4'port'=>env('REDIS_PORT',6379),5'database'=>0,6'read_timeout'=>60,7],You may interact with Redis by calling various methods on theRedisfacade. TheRedis facade supports dynamic methods, meaning you may call anyRedis command on the facade and the command will be passed directly to Redis. In this example, we will call the RedisGET command by calling theget method on theRedis facade:
1<?php 2 3namespace App\Http\Controllers; 4 5use App\Http\Controllers\Controller; 6use Illuminate\Support\Facades\Redis; 7 8classUserControllerextendsController 9{10/**11 * Show the profile for the given user.12 *13 *@paramint $id14 *@returnResponse15*/16publicfunctionshowProfile($id)17 {18$user=Redis::get('user:profile:'.$id);19 20returnview('user.profile',['user'=>$user]);21 }22}Of course, as mentioned above, you may call any of the Redis commands on theRedis facade. Laravel uses magic methods to pass the commands to the Redis server, so pass the arguments the Redis command expects:
1Redis::set('name','Taylor');2 3$values=Redis::lrange('names',5,10);Alternatively, you may also pass commands to the server using thecommand method, which accepts the name of the command as its first argument, and an array of values as its second argument:
1$values=Redis::command('lrange', ['name',5,10]);You may get a Redis instance by calling theRedis::connection method:
1$redis=Redis::connection();This will give you an instance of the default Redis server. You may also pass the connection or cluster name to theconnection method to get a specific server or cluster as defined in your Redis configuration:
1$redis=Redis::connection('my-connection');Pipelining should be used when you need to send many commands to the server in one operation. Thepipeline method accepts one argument: aClosure 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:
1Redis::pipeline(function($pipe) {2for ($i=0;$i<1000;$i++) {3$pipe->set("key:$i",$i);4 }5});Laravel provides a convenient interface to the Redispublish andsubscribe commands. These Redis commands allow you to listen for messages on a given "channel". You may publish messages to the channel from another application, or even using another programming language, allowing easy communication between applications and processes.
First, let's setup a channel listener using thesubscribe method. We'll place this method call within anArtisan command since calling thesubscribe method begins a long-running process:
1<?php 2 3namespace App\Console\Commands; 4 5use Illuminate\Console\Command; 6use Illuminate\Support\Facades\Redis; 7 8classRedisSubscribeextendsCommand 9{10/**11 * The name and signature of the console command.12 *13 *@varstring14*/15protected$signature='redis:subscribe';16 17/**18 * The console command description.19 *20 *@varstring21*/22protected$description='Subscribe to a Redis channel';23 24/**25 * Execute the console command.26 *27 *@returnmixed28*/29publicfunctionhandle()30 {31Redis::subscribe(['test-channel'],function($message) {32echo$message;33 });34 }35}Now we may publish messages to the channel using thepublish method:
1Route::get('publish',function() {2// Route logic...3 4Redis::publish('test-channel',json_encode(['foo'=>'bar']));5});Using thepsubscribe method, you may subscribe to a wildcard channel, which may be useful for catching all messages on all channels. The$channel name will be passed as the second argument to the provided callbackClosure:
1Redis::psubscribe(['*'],function($message,$channel) {2echo$message;3});4 5Redis::psubscribe(['users.*'],function($message,$channel) {6echo$message;7}); Laravel is the most productive way to
build, deploy, and monitor software.