Reputation: 1
I'm starting my studies at LARAVEL and I still have some difficulties, I would like help from the community. I have the following information in the table
id created_at updated_at day period temperature
1 2021-01-22 18:36:58 0000-00-00 00:00:00 2020-12-12 MORNI 36.50
2 2021-01-22 18:36:58 0000-00-00 00:00:00 2020-11-13 MORNI 33.60
3 2021-01-22 18:36:58 0000-00-00 00:00:00 2020-10-14 MORNI 32.30
4 2021-01-22 18:36:59 0000-00-00 00:00:00 2020-12-12 AFTER 37.40
5 2021-01-22 18:36:59 0000-00-00 00:00:00 2020-11-13 AFTER 36.20
6 2021-01-22 18:36:59 0000-00-00 00:00:00 2020-10-14 AFTER 34.40
7 2021-01-22 18:36:59 0000-00-00 00:00:00 2021-01-21 AFTER 29.10
8 2021-01-22 18:37:00 0000-00-00 00:00:00 2020-12-14 NIGHT 33.90
I need the json exit to be that way (group by period)
{
"name":"MORNI",
"data":[
{
"x":"2020-12",
"y":36.50
}, {
"x":"2020-11",
"y":33.60
}
]
},
{
"name":"AFTER",
"data":[
{
"x":"2020-12",
"y":37.40
},etc
]
},
{
"name":"NIGHT",
"data":[
{
"x":"2020-12",
"y":33.90
},etc
]
}
how to build the controller?
public function index()
{
$reg = Climate::orderBy('Day')->get();
$data = [];
...
return response()->json( $data );
}
I appreciate any help
Upvotes: 0
Views: 214
Reputation: 31
I think the output pattern you shared can't be done by Eloquent directly. Hope this might help you:
public function index()
{
$reg = Climate::orderBy('Day')->get();
$data = [];
foreach($reg as $item){
if(!isset($data[$item->period])){
$data[$item->period]['name'] = $item->period;
$data[$item->period]['data'] = [];
}
array_push($data[$item->period]['data'], ["x" => $item->day, "y" => $item->temperature ]);
}
return response()->json( $data );
}
Upvotes: 1