Laravel 9 ChartsJs Example Tutorial

Using this Laravel 9 ChartJS Chart Example Tutorial; you will learn how to create and use Charts Js chart in laravel application. Through this example we show laravel 8 charts js chart use in laravel blade dynamically.

Chartjs is a js library, this library through you can simply use simple example for Line Charts, Bar Charts, Pie Charts, Area Charts, etc using chartjs js. In this example, we will create some dummy users records and then we will display a line chart with all months of current years.

Step 1: Install Laravel App

First create new laravel 9 application adding the following command in terminal.

composer create-project --prefer-dist laravel/laravel laravel-app

Now Go into the app:

laravel-app

Step 2: Connect App to Database

Open the .env file and add your database credentials such as database name, username equally important password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Step 3: Add Route

In this step, Navigate to routes folder and open web.php. Then add the following routes into web.php file:

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ChartController;

Route::get('users-stats', [ChartController::class, 'userStats']);

Step 4: Create Controller & Update Code

In this step you need to create a new controller using the following command;

php artisan make:controller ChartController

Next open the app/Http/Controllers/ChartController.php.file and update the below code on it.

<?php

namespace App\Http\Controllers;

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

class ChartController extends Controller
{
    public function userStats()
    {
        $year = date('Y');

        $users = User::select(\DB::raw("COUNT(*) as count"))
                    ->whereYear('created_at', $year)
                    ->groupBy(\DB::raw("Month(created_at)"))
                    ->pluck('count');

    	return view('charts')->with([
            'users' => json_encode($users)
        ]);
    }
}

Step 5: Create blade file

In this step, navigate to resources/views/ folder and create one blade view files that name charts.blade.php file. Then open the resources\views\charts.blade.php file and put the below code on it;

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 9 Highcharts Example</title>
</head>

<body>
<h1 class="text-center">Laravel 9 Highcharts Example</h1>
<div class="container">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading">Dashboard</div>
                <div class="panel-body">
                    <canvas id="canvas" height="100" width="200"></canvas>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js" charset="utf-8"></script>
<script>
    let year = ['Jan', 'Feb', 'March', 'April', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];
    let users = <?php echo $users; ?>;


    var barChartData = {
        labels: year,
        datasets: [{
            label: 'View',
            backgroundColor: "rgba(151,187,205,0.5)",
            data: users
        }]
    };


    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: 'Monthly grawing users'
                }
            }
        });


    };
</script>
</html>

Step 6: Generate Dummy Records

First run the migration command to generate users table in database;

php artisan migrate

Here, we need to add some dummy records on users table as monthly wise. you can create dummy records using laravel tinker command as bellow:

php artisan tinker
User::factory()->count(30)->create()

Step 7: Run Laravel Project

Finally, we need to execute the following PHP artisan serve command to start laravel chartjs example app:

php artisan serve

Now, open browser and put the below url in browser:

http://localhost:8000/users-stats

I hope you enjoy with laravel chartjs to show chart.

Leave a Comment