</> Code The Pixel

CakePHP 4 Visualized Data Using ChartJS

Asyraf Wahi Anuar - April 02, 2022

Estimated reading time: 2 minutes, 42 seconds

Visualizing data into charts is very useful to make the data more presentable and readable. Many free, open-source chart libraries are available for a developer to use, e.g. ChartJS, ApexCharts, D3.js and others. This tutorial will demonstrate how to count and visualize data in CakePHP 4 using ChartJS. ChartJS is a free, open-source javascript library that supports various chart types, e.g., bar, pie, line, area, radar, scatter, and others. It is recommended to read the ChartJS official documentation.

Install ChartJS Using CDN
Load the following ChartJS CDN at the top of your page.

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>


Data Count/Sum and Visualized in ChartJS
Assuming that we have a user table that contains information related to title, category, status, hits (views) and created. From this information, we can:

1. Count total articles for each category [tutorial, blog, project] (Bar Chart)
The following codes are used to count the total of articles published in each category. Load the code into the controller.

$this->set('count_tutorial', $this->Articles->find()->where('category' => 'tutorial')->count());
$this->set('count_blog', $this->Articles->find()->where('category' => 'blog')->count());
$this->set('count_project', $this->Articles->find()->where('category' => 'project')->count());

The above codes will provide the value for the total articles available in each of the categories. The value can be passed to ChartJS as shown below:

<canvas id="articleCategory" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('articleCategory').getContext('2d');
var articleCategory = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Tutorial', 'Blog', 'Project'],
        datasets: [{
            label: '# of Category',
            data: [<?= json_encode($count_tutorial); ?>, <?= json_encode($count_blog); ?>, <?= json_encode($count_project); ?>],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
                'rgba(255, 206, 86, 0.2)',
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
                'rgba(255, 206, 86, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            title: {
                display: true,
                text: 'Total Article in Each Category'
            },
        legend: {
                display: false,
                labels: {
                    color: 'rgb(255, 99, 132)'
                }
            },
        }
    },
});
</script>    


2. Count total articles for each status [published, archived] (Pie Chart)
The next example shows the code to count and sum the total articles based on the status, whether it is currently published or archived. 

$this->set('published', $this->Articles->find()->where('status' => '1')->count());
$this->set('archived', $this->Articles->find()->where('status' => '0')->count());

To generate the chart, passed the sum value to the ChartJS script as shown below:

 <canvas id="articleStatus" width="400" height="400"></canvas>
<script>
var ctx = document.getElementById('articleStatus').getContext('2d');
var articleStatus = new Chart(ctx, {
    type: 'pie',
    data: {
        labels: ['Published', 'Archived'],
        datasets: [{
            label: '# of Status',
            data: [<?= json_encode($published); ?>, <?= json_encode($archived); ?>],
            backgroundColor: [
                'rgba(255, 99, 132, 0.2)',
                'rgba(54, 162, 235, 0.2)',
            ],
            borderColor: [
                'rgba(255, 99, 132, 1)',
                'rgba(54, 162, 235, 1)',
            ],
            borderWidth: 1
        }]
    },
    options: {
        plugins: {
            title: {
                display: true,
                text: 'Total Published/Archived Articles'
            },
        legend: {
                display: false,
                labels: {
                    color: 'rgb(255, 99, 132)'
                }
            },
        }
    },
});
</script> 

   
That's all. Happy coding :)


Cite this article (APA 6th Edition)

Popular
CakePHP 4 Print PDF Using CakePDF
May, 17 2020
CakePHP 4 Authentication Using Auth...
May, 14 2020
CakePHP 4 Sending Email
February, 01 2022
CakePHP 4 jQuery Date Time Picker
October, 01 2018
CakePHP 4 Export To CSV
May, 29 2020
CakePHP 4 Authentication Using...
May, 11 2020
CakePHP 4 Find, Sort & Count
June, 02 2020
Share
Sharing Link
Click the icon to share