Tongat
Tongat

Reputation: 141

How to fix php json_encode using Redis and Laravel?

when i try to make json response, first response not Json value, like this.

{
"success": true,
"data": "{\"name\":\"Adventure\",\"slug\":\"adventure\"}"
}

but when i try for 2nd,3th,....., response is Json value.

{
"success": true,
"data": {
    "name": "Adventure",
    "slug": "adventure"


   }
}

how to fix it, this case i'm using Laravel. this is my code,

$slug = $request->header()['slug'][0];
$redis = Redis::get('genre_details_'.$slug);
$redis = json_decode($redis);

if(empty($redis)){
    $query = Genre::select('name', 'slug')->where('slug', $slug)->first();

    if(empty($query)){
        return response()->json(['success' => false, 'message' => 'slug code is wrong!'],406);
    }

    Redis::set('genre_details_'.$slug,json_encode($query));
    Redis::expire('genre_details_'.$slug, 7200);

    $redis = Redis::get('genre_details_'.$slug);
}

$response = [
    'success' => true,
    'data' => $redis
];

return response()->json($response);

http://sandbox.onlinephpfunctions.com/code/f13947f25f7f6078269ab697c62edc126bcd9afe

Upvotes: 0

Views: 963

Answers (1)

u_mulder
u_mulder

Reputation: 54841

Move $redis = json_decode($redis); after if(empty($redis)){ } code.

Because when you put data to redis - you put it there json_encoded. But not decode it. And when your get data from redis for 2nd, 3rd time - you decode it. So, you need to decode your data everytime.

Upvotes: 1

Related Questions