In this article, we will learn how to use chart.js in laravel 8. Chart Js is a js library, We can use bar chart, line chart, area chart, column chart, etc, and it also provides several themes.


Database Structure

open .env file and connect to your database and import following data to show users in particular year.


-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Feb 03, 2021 at 04:45 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 7.4.14

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;

--
-- Database: `php-tutorial`
--

-- --------------------------------------------------------

--
-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `username` varchar(250) NOT NULL,
  `created_at` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `username`, `created_at`) VALUES
(1, 'stint', '2018-02-11 21:04:22'),
(2, 'stint', '2021-02-01 21:04:41'),
(3, 'stint', '2021-02-11 21:04:22'),
(4, 'stint', '2021-02-01 21:04:41'),
(5, 'rakesh', '2021-02-03 21:06:14'),
(6, 'mohan', '2021-02-03 21:06:14'),
(7, 'stint', '2018-02-11 21:04:22'),
(8, 'stint', '2018-02-11 21:04:22'),
(9, 'stint', '2018-02-11 21:04:22');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `users`
--
ALTER TABLE `users`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;



Follow some steps to use chart.js in laravel 8:


Step 1: 

make routes

routes/
┗ web.php

use App\Http\Controllers\ChartJsController;
Route::get('chartjs', [ChartJsController::class, 'index'])->name('chartjs.index');


Step 2: Create Controller

create controller file via artisan command

php artisan make:controller ChartJsController 


app/Http/
┣ Controllers/
┃ ┣ ChartJsController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\User;
use DB;
use Carbon\Carbon;

class ChartJsController extends Controller
{
    //
    public function index()
    {
        $year = ['2017','2018','2019','2020','20121'];

        $user = [];
        foreach ($year as $key => $value) {
            $user[] = User::where(\DB::raw("DATE_FORMAT(created_at, '%Y')"),$value)->count();
        }

    	return view('chartjs')->with('year',json_encode($year,JSON_NUMERIC_CHECK))->with('user',json_encode($user,JSON_NUMERIC_CHECK));
    }
}


Step 3: Create view

create view as blade file

views/
┣ chartjs.blade.php

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    </head>
    <body>


        <div class="container">
            <div class="row">
                <div class="col-md-10 offset-md-1">
                    <div class="panel panel-default">
                        <div class="panel-heading">Dashboard</div>
                        <div class="panel-body">
                            <canvas id="canvas" height="280" width="600"></canvas>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
        <script>
            var year = <?php echo $year; ?>;
            var user = <?php echo $user; ?>;
            var barChartData = {
                labels: year,
                datasets: [{
                        label: 'User',
                        backgroundColor: "#45f6ff",
                        data: user
                    }]
            };

            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: '#c1c1c1',
                                borderSkipped: 'bottom'
                            }
                        },
                        responsive: true,
                        title: {
                            display: true,
                            text: 'Yearly User Joined'
                        }
                    }
                });
            };
        </script>


    </body>
</html>


Output: