I have a MySQL table like this:
+------+-----------------+---------+------------+
| id | name | refferal| reference |
+------+-----------------+---------+------------+
| 1 | Alex Muller | 1 | null |
| 2 | John Doe | 2 | 1 |
| 3 | Tom Foe | 3 | 1 |
| 4 | Harry Pott | 4 | 3 |
| 5 | Kate Garry | 5 | 3 |
| 6 | Mike Blue | 6 | 4 |
+------+-----------------+---------+------------+
(more data than this…)
I need to turn that data to JSON file with Laravel. Like this:
[{"id":1,"name":"Alex Muller","parent":0},
{"id":2,"name":"John Doe","parent":1},
{"id":3,"name":"Tom Foe","parent":1},
{"id":4,"name":"Harry Pott","parent":3},
{"id":5,"name":"Kate Garry","parent":3},
{"id":6,"name":"Mike Blue","parent":4}]
At the and of this I will get a tree view like this:
I just made this json file with my own write. And I don’t know what to do. I’m waiting your answers. Thank you.
2
Answers
If you want to add extra fields like "parent" in your example you can use map on the collection:
Or if you just want to encode the model attributes, you can use toJson serialization directly with the collection:
for further information, refer to the links:
https://laravel.com/docs/collections
https://laravel.com/docs/eloquent-serialization#serializing-to-json
On the model get the keys you need and then with map() change the key
reference
toparent
, on that check if is null thereference
to put a 0 then encode the array for json with json_encode.Then just make a json with that array:
echo json_encode($array);