JustinTime JustinTime - 2 months ago 5
JSON Question

Loop data into json?

I wanna loop every appointment and put it in json like this :

[
{
"id":"1",
"title":"Test 1",
"start":"2016-09-16 12:00:00",
"end":"2016-09-16 14:00:00",
"allDay":false
},

{
"id":"2",
"title":"Test 2",
"start":"2016-09-15 12:00:00",
"end":"2016-09-15 14:00:00",
"allDay":false
}
]


I have a table
appointments
in the database.

id | title | appointment_date_start | appointment_date_end |
-------------------------------------------------------------
1 | Test 1 | 2016-09-16 12:00:00 | 2016-09-16 14:00:00 |
2 | Test 2 | 2016-09-15 12:00:00 | 2016-09-15 14:00:00 |


In my
feed.blade.php
I get all the data.
So i can do:

@foreach ($appointments as $appointments)

{{ $appointment->id }}
{{ $appointment->title }}
{{ $appointment->appointment_date_start }}
{{ $appointment->appointment_date_end }}

@endforeach


This outputs the data from the database. But how do I foreach it in a array?

Like

$event_array[] = array(
'id' => {{ $appointment->id }},
'title' => {{ $appointment->gender }},
'start' => {{ $appointment->appointment_date_start }},
'end' => {{ $appointment->appointment_date_end }},
'allDay' => false
);


Edit

I tried this in my public function

public function feed()
{
$feed = Appointment::all();
return $feed->toJson();
return view('appointments/feed');
}


This is what I get

{
id: 35,
user_id: 1,
gender: "men",
appointment_date_start: "2016-09-14 20:00:00",
appointment_date_end: "2016-09-14 20:40:00",
created_at: "2016-09-16 08:16:16",
updated_at: "2016-09-16 08:16:16"
}


I need to remove
gender, created_at and updated_at
and appointment_date_start should be start and appointment_date_end should be end? Is this possible?

Answer

If you want to remove created_at and updated_at, just don't select the attributes while fetching the data from the database:

$feed = Appointment::select('id', 'user_id', 'appointment_date_start as start', 'appointment_date_end as end')->get(); 
// leave created_at and updated_at
// select('old as new') to change the attribute name

Then encode the array into json with json_encode

return json_encode($feed);
Comments