0

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

2
  • just pass the $reg instead of $data . return response()->json( $reg ); Commented Jan 26, 2021 at 14:22
  • Thank you for your help; but in this model I don't have the desired return (grouped by period) .. I need this format because I print it on the apexcharts Commented Jan 26, 2021 at 14:51

1 Answer 1

1

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 );
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you very much, met my need perfectly
@RodrigoReichert, please give an upvote if this answer helped you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.