Mr Robot
Mr Robot

Reputation: 897

Append query result to a existing json object

i have the result of 2 query in 2 variables and i have a JSON object i want to append the query result to that JSON and then return it to the user

in may controller i have all the result

if ($request->wantsJson()) {

    $agent_id = $request->user()->id;

    $drivers_cout = Driver::all()->count();

    $drivers_cout_by_agent = Driver::where(['agent_id' => $agent_id])->get()->count();

    return $request->user();
}

//the result of  $request->user();

  #attributes: array:12 [
    "id" => 201702
    "name" => "Agent"
    "email" => "[email protected]"
    "phone_number" => "966355826"
  ]

//and i want something like

  #attributes: array:12 [
    "id" => 201702
    "name" => "Agent"
    "email" => "[email protected]"
    "phone_number" => "966355826"
    "drivers_count" => "96"                        //How do i append these two
    "drivers_cout_by_agent" => "16"         
  ]

thank you

Upvotes: 1

Views: 1566

Answers (3)

Mark Kasson
Mark Kasson

Reputation: 1710

You appear to have an array and just want to add a few elements to it, so this can do it.

$tmp= $request->user();
$tmp['driver_count'] = (where you get it from);
$tmp['count_by_id'] = (where you get it from);
return $tmp;

(Sorry for lack of detail, I'm on my cell. If this is what you need, I'll expand/correct later or delete if it's not. Wanted to get this to you quickly.)

Upvotes: 1

RiggsFolly
RiggsFolly

Reputation: 94672

Adding data to an array is simply a case of putting data into the array with the index name you want it to have

if ($request->wantsJson()) {

    $agent_id = $request->user()->id;              

    $drivers_count = Driver::all()->count();         //<-- fixed spelling

    $drivers_cout_by_agent = Driver::where(['agent_id' => $agent_id])->get()->count();

    $arr = $request->user();
    $arr['drivers_count'] = $drivers_count;
    $arr['drivers_cout_by_agent'] = $drivers_cout_by_agent
    return $arr;
}

Upvotes: 2

Patryk Uszyński
Patryk Uszyński

Reputation: 1119

According to Serializing Models & Collections. You can simply serialize it json or array by:

return $request->user()->toJson();
// or
return $request->user()->toArray();

There is also a section about appending data to json: Appending Values To JSON. But in your situation you can serialize your data to array, append your values and encapsulate it to json.

$returnData = $request->user()->toArray();
$returnData['foo'] = 'bar';

return json_encode($returnData);

Upvotes: 0

Related Questions