0

Laravel v.5.8:

I want to group each child relation budgets and json serialize it.

$monthbudgets = \App\BudgetMonth::where('month', $curmonth)->with("budgets")->get(); foreach ($monthbudgets as $month) { $month->budgets = $month->budgets->groupBy("customer_id"); } dd($monthbudgets[8]); 

which will return:

//laravel collection of "budgets" ...[ 1 => [ 0 => [] 1 => [] ], 5 => [ 0 => [] ] ]... 

but using dd($monthbudgets[8]->jsonSerialize()), it will return:

//array of "budgets" ...[ 0 => [] 1 => [] 2 => [] ]... 

Looks like it flattens it and removes the keys (1, 5).

I'm also open to suggestions for minimizing the grouping loop. I tried

->with(["budgets" => function ($query) { $query->groupBy("customer_id"); }])->get(); 

which will result in

Syntax error or access violation: 1055 'budgets.id' isn't in GROUP BY (...)

2
  • See this answer stackoverflow.com/questions/8940825/… Commented Oct 29, 2019 at 14:28
  • When returning a json response you can just return the collection and it will be serialized by default. For keys try using keyBy and maybe transform Commented Oct 29, 2019 at 14:30

1 Answer 1

1

Laravel's jsonSerialize will call toArray:

// Model.php public function toArray() { return array_merge($this->attributesToArray(), $this->relationsToArray()); } 

which merges the attributes and then the relations which makes it overwrite the attribute you've set.

You can set the relation with setRelation

foreach ($monthbudgets as $month) { $month->setRelation('budgets', $month->budgets->groupBy("customer_id")); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.