Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kovbo's avatar
Level 1

How to build an API to show statistics on a chart?

I store each new website visit to a database.

Then, I want to shows visits statistics for the last days/weeks/year on a chart.

I expect the API response to look like:

dates: //chart labels
[
"2020-06-29",
"2020-06-30",
"2020-07-01"
],
visits: //chart data
[
20,
30,
40
]

Do you have any ideas on how to build a controller for such an API endpoint?

Is it possible to make it fast and avoid massive calculations and database parsing showing statistics for the whole year?

0 likes
1 reply
bobbybouwmann's avatar

You can avoid lots of problems by only fetching the data you really need. Already grouping the data in your query and doing the counts in there helps a lot.

To create such a response you can simply map your items to an array and convert that to JSON. You can use the collection methods to do that. Do note that the collection methods are amazing, they also are a bit slower with large data sets.

Fetching the correct data and then converting it is the best approach here.

Please or to participate in this conversation.