I have started to work with laravel. It is quite interesting to work. I have started to use the features of laravel. I have started to use redis
by install redis server in my system and change the configuration for redis in app/config/database.php
file. The redis is working fine for the single variables by using set
. i.e.,
$redis = Redis::connection();
$redis->set('name', 'Test');
and i could able to get the value by using
$redis->get('name');
But i want to set the array by using set
function. If i try do that getting the following error
strlen() expects parameter 1 to be string, array given
I have tried by using following codes.
$redis->set('name', array(5, 10));
$values = $redis->lrange('names', array(5, 10));
and if i use
$values = $redis->command('lrange', array(5, 10));
getting the following error
'command' is not a registered Redis command
Can any one explain me the problem and is that possible with redis?…we can set the array values using redis
?
This has been answered in the comments but to make the answer clearer for people visiting in the future.
Redis is language agnostic so it won’t recognise any datatype specific to PHP or any other language. The easiest way would be to serialise
/ json_encode
the data on set then unserialise
/json_decode
on get.
Example to store data using json_encode
:
use Illuminate\Support\Facades\Redis;
$redis = Redis::connection();
$redis->set('user_details', json_encode([
'first_name' => 'Alex',
'last_name' => 'Richards'
])
);
Example to retrieve data using json_decode
:
use Illuminate\Support\Facades\Redis;
$redis = Redis::connection();
$response = $redis->get('user_details');
$response = json_decode($response);
Answer:
Redis Supports Multiple Data Structure Types Like Hash, Link List And Array.
But You Have to User Proper Methods from Laravael Redis Facade Like:
//set user_details key and below key_values
Redis::hmset('user_details',["firstName" => "Abi", "lastName" => "logos"]);
//get all as an Associate Array
Redis::hgetall('user_details');
//get just The Keys as an Array
Redis::hkeys('user_details');
further information:
https://redis.io/commands#hash
Answer:
In your controller, you can add such function:
use Illuminate\Support\Facades\Redis;
private function getUsers() {
if ($users = Redis::get('users.all')) {
return json_decode($users);
}
$users = User::all();
Redis::set('users.all', $users);
return $users;
}
Then in your index
method (or others) you can do this:
public function index(Request $request) {
$users = $this->getUsers();
}
Source: accepted answer and this.