Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel how to add new field in query result

How can I add new field in each item, I have used put() but it only add on the last item.

return self::where('latest', 1)
            ->where('competitionId',$competitionId)
            ->orderBy('won','desc')
            ->orderBy('teamName','asc')
            ->get(['teamName','played','won','lost','percentage', 'streak'])
            ->put('test', ['123', '345'])
            ->toJson();

Result:

{
"0": {"teamName": "A"},
"1": {"teamName": "B"},
"2": {"teamName": "C", "test": ['123', '345']},
}

Expected output:

{
"0": {"teamName": "A", "test": "qwerty"},
"1": {"teamName": "B", "test": "qwerty"},
"2": {"teamName": "C", "test": "qwerty"},
}
like image 562
PenAndPapers Avatar asked Jun 14 '17 01:06

PenAndPapers


1 Answers

you can use map()

->map(function ($item) {
  $item['test'] = ['123', '345'];
  return $item;
});
like image 54
LF00 Avatar answered Oct 09 '22 05:10

LF00