0

Relatively new to Laravel and trying to create a REST api that will have as a response a json that is split between rows and cols of a query

So, the code used to generate the json is:

$r = array(
        'cols' => array_keys(get_object_vars(Dd_hr::take(2)->get())),
        'rows' => Dd_hr::take(2)->get()
    );
return response()->json($r, 201);

Basically, the json should look something like:

{"cols":[{"id", "user_name"}],"rows":[{"710206","user"}]}

But in fact it looks like:

{"cols":[],"rows":[{"id":"710206","user_name":"user"}]}

Could someone help me to solve this issue?

The result of dd(Dd_hr::take(2)->get()->toArray()):

array:2 [▼
  0 => array:27 [▼
    "rn" => "1"
    "id" => "710206"
    "user_name" => "user"
  ]
  1 => array:27 [▼
    "rn" => "2"
    "id" => "710207"
    "user_name" => "user"
  ]
]
rosuandreimihai
  • 656
  • 3
  • 16
  • 39

1 Answers1

1

Didn't find a way to do this properly so here goes the good old array_map.

This doesn't remove the "rn" key. If you want to chose the keys in the select you can, it'll even make creating the JSON easier since you'll already have the 'cols'.

$res_array = Dd_hr::take(2)->get()->toArray();

$cols = array_keys($res_array[0]);

$rows = array_map(function($row){
            return array_values($row);
        }, $res_array);

return response()->json(array('cols'=>$cols, 'rows'=>$rows), 201);

This returns : "{"cols":["rn","id","user_name"],"row":[["1","710206","user"],["2","710207","user"]]}"