Bas Bas - 2 months ago 10
JSON Question

How can I update or delete a record from the JSON output using Laravel and Predis

I started a few months ago with Laravel and I want to implement Redis.

How and what is the best way to update or delete 1 or more records from

$test
.

$allarticles = Article::all();
$client = Redis::connection();
$client->set('articles', $allarticles->toJson() );
$test = $client->set('articles');


Output:

[{
"id":1,"title":"xQeMKGefAW","content":"44cuxAqVDS@gmail.com","created_at":null,"updated_at":null},{
"id":2,"title":"a5wpRVRBNZ","content":"SsH9U5kF32@gmail.com","created_at":null,"updated_at":null},{
"id":3,"title":"QF5xhsMh7d","content":"8erXnIojAM@gmail.com","created_at":null,"updated_at":null},{
"id":4,"title":"gQVbDNbcmD","content":"27feouH6vc@gmail.com","created_at":null,"updated_at":null},{
"id":5,"title":"FsOnoABBTg","content":"2qNutidwKZ@gmail.com","created_at":null,"updated_at":null},{
"id":6,"title":"89sS4UASJl","content":"cQku7DBKSB@gmail.com","created_at":null,"updated_at":null},{
"id":7,"title":"gpT3hO43V1","content":"EhzyEylbgw@gmail.com","created_at":null,"updated_at":null},{
"id":8,"title":"1DKvbBn7yV","content":"0cSAxi9if3@gmail.com","created_at":null,"updated_at":null},{
"id":9,"title":"pRr2LgzezC","content":"Aam0uuWLlF@gmail.com","created_at":null,"updated_at":null}


Answer:

$allarticles = Article::all()->keyBy('id'); $client = Redis::connection();
$newarray = array();
foreach ( $allarticles->toArray() as $key => $value ){
$newarray[$key] = json_encode($value); } $client->hmset('testtest', $newarray);
$qwerty = $client->HGETALL('testtest');
print_r($qwerty);
}

Answer

Instead of storing the whole json as a string, store them in a hashmap using hmset command, id is the member and rest of the json is the value.

http://redis.io/commands#hash

To set the json:

hmset articles 1 {"title":"xQeMKGefAW","content":"44cuxAqVDS@gmail.com","created_at":null,"updated_at":null} 2 {"title":"xQeMKGefAW","content":"44cuxAqVDS@gmail.com","created_at":null,"updated_at":null} and so on

To retrieve the whole json:

hgetall articles

To update one or more values use HMSET

To delete one or more values use HDEL

Hope this helps.