Chartjs-How to generate dynamic bar chart in laravel using chart.js

0👍

From what I see in your function for rendering the chart you are passing the data for each dataset as a parameter. Instead, modify your backend to fetch the data for all datasets to look like:

{
  "Loans": [2],
  "Payments": [3]
  ...
}

I’ve added a function in my JS to set the data accordingly for my chart:

function getChartData(data) {
let chartData = {
    labels: ["# of records"], // on your case this is enough
    datasets: []
};
Object.keys(data).forEach(function(label, index) {
    chartData.datasets.push({
        label: label,
        data: Object.values(data[label]),
        borderColor: colors[index]
    });
});

return chartData;
}

colors is just an array with hex color strings, as many as you like. I’ve created a function to generate a random color if the datasets become too many.

Then when I create my chart I simply pass the result of that function to the data of the chart.

You’ll have modify this depending on your backend. Check this fiddle.

Leave a comment