In this tutorial we’re going to learn how to connect redis database in laravel project. I have mentioned in step by step ini very easy way.
What is Redis ?
Redis is an open-source, in-memory data store that functions as a versatile tool for developers. Here’s a breakdown of its key characteristics:pen_spark
In-Memory Storage:
- Data resides in RAM, enabling extremely fast access times (sub-milliseconds) compared to traditional disk-based databases. This makes it ideal for real-time applications and caching frequently accessed data.
Key-Value Store:
- Data is organized as key-value pairs, similar to a dictionary. Keys are unique identifiers used to retrieve their corresponding values. This simple structure allows for quick data manipulation.
How to connect in redis in laravel Project ?
1st step open your project and run below command
composer require predis/predis
2nd step go to below path
config/app.php
Paste below code in app.php code
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'default' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_DB', 0),
],
'cache' => [
'host' => env('REDIS_HOST', '127.0.0.1'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', 6379),
'database' => env('REDIS_CACHE_DB', 1),
],
],
Next to create controller
php artisan make:controller RedisController
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
class RedisController extends Controller
{
public function index(){
Redis::set('users:1:first_name','amit');
return 'redis testing amit';
}
}
Next go to web.php and put below code
Route::get('/redis', [App\Http\Controllers\RedisController::class, 'index']);
Next go to .env and put below code
REDIS_CLIENT=predis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
Next to open your server and check
Next go to redis stack and check data is coming or not
Now data inserted successfully.