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

vipin93's avatar
Level 13

how to count students group by year of admission?

I try to make chart using chartsjs. I try to count students which grouped by year of admission but I'm unable to make it here is my code contoller

$chart = Student::select(DB::raw("SUM(id) as count"))
                       ->orderBy("year_of_admission")
                       ->groupBy(DB::raw("year(year_of_admission)"))
                       ->get()->toArray();
                $chart = array_column($chart, 'count');

        $students = Student::with('city')->get();
      

        return view('home', compact('students''))
              ->with('chart',json_encode($chart,JSON_NUMERIC_CHECK));

my script

 <script  src="/js/Chart.bundle.min.js"></script>
   <script>
    var year = ['2005','2006','2007','2008','2009','2010','2011','2012','2013','2014','2015'];
    var data_students = <?php echo $chart; ?>;
    

    var barChartData = {
        labels: year,
        datasets: [{
            label: 'Students',
            backgroundColor: "rgba(220,220,220,0.5)",
            data: data_students
        }]
    };

    window.onload = function() {
        var ctx = document.getElementById("canvas").getContext("2d");
        window.myBar = new Chart(ctx, {
            type: 'bar',
            data: barChartData,
            options: {
                elements: {
                    rectangle: {
                        borderWidth: 2,
                        borderColor: 'rgb(0, 255, 0)',
                        borderSkipped: 'bottom'
                    }
                },
                responsive: true,
                title: {
                    display: true,
                    text: 'Yearly Students Addmission'
                }
            }
        });

    };
</script>

Thanks

0 likes
2 replies
vipin93's avatar
vipin93
OP
Best Answer
Level 13

"SUM(id) as count" => "count(*) as count"

Please or to participate in this conversation.