0

I want to get users list as per distance and in user DB I stored user images in json format. When I use DB::table it return as string not as array.

Please Help me.

My Controller:

$doc = DB::table( 'users' )
            ->select(
                'id',
                'name',
                'image',
                'latitude',
                'longitude' )
            ->selectRaw( "{$getDistance} AS distance" )
            ->orderBy( 'distance' )
            ->get();

CURRENT JSON RESPONSE:

{
"name": "User One",
"image": "[\"f0f159c7238b8c9a1a3e5c9bd48de2a5cJ8Y4ssqzcuoWJAS1614581337EC2fGzmRCjf9wphI.webp\", 
         \"f0f159c7238b8c9a1a3e5c9bd48de2a5tvof9EarZgvupGpa1614581337zvPSnQchCjSL9lZS.webp\"]",
}

What I WANT TO GET:

{
"name": "User One",
"image": ["f0f159c7238b8c9a1a3e5c9bd48de2a5cJ8Y4ssqzcuoWJAS1614581337EC2fGzmRCjf9wphI.webp", 
         "f0f159c7238b8c9a1a3e5c9bd48de2a5tvof9EarZgvupGpa1614581337zvPSnQchCjSL9lZS.webp"],
}
3
  • how do you return your json in controller? Commented Mar 6, 2021 at 5:56
  • maybe it is because of distance, you just do this $doc = DB::table( 'users' ) ->select( 'id', 'name', 'image', 'latitude', 'longitude' ) ->get();and check what you get Commented Mar 6, 2021 at 6:02
  • 1
    Why not use Eloquent ORM Query? Commented Mar 6, 2021 at 6:06

1 Answer 1

1

you can use Jsonencode or jsondecode before send the response.

i would use $doc->image = json_encode($doc->image());

and then

return response()->json('data' => $doc);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.