Laravel 9 Dynamic Chart Example Using Chart Js
Hello Artisan,
In this laravel 9 chartjs tutorial, I will discuss how to show data on chartjs from database in Laravel 9. So in this laravel 9 chartjs tutorial, you will learn how to create chart in Laravel 9.
In this tutorial, I am going to show you how to use chartjs in laravel with proper examples. whenever you need to add chart in laravel 9 applications. then you can easily use the following example you have to fetch data from database and then set it in the chart js function,
Today, I will help you to learn how to add charts using chart js in laravel 9. I will explain step by step laravel 9 chart js example. you can simply use Line Charts, Bar Charts, Pie Charts, Area Charts, etc. we will create a line chart with laravel 9.
Chart js is a js library, this library through we can use bar charts, line chart, area chart, column chart etc. Highcharts is an open-source chart library. Chart js also provide several theme and graph that way you can use.
Preview
Step 1: Install Laravel 9
This step is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:
composer create-project laravel/laravel example-app
Step 2: Create Route:
Now we will create a simple route for creating a simple line chart. so let's add simple routes like below:
routes/web.php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\HighchartController;
Route::get('chart', [HighchartController::class, 'index']);
Step 3: Create Controller:
Here, we will create a new controller as HighchartController. so let's add the below code on that controller file.
app/Http/Controllers/HighchartController.php
namespace App\Http\Controllers;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class HighchartController extends Controller
{
public function index()
{
$users = User::select(DB::raw("COUNT(*) as count"))
->whereYear('created_at', date('Y'))
->groupBy(DB::raw("Month(created_at)"))
->pluck('count');
return view('welcome', compact('users'));
}
}
Step 4: Create Blade File:
here, we need to create a blade file and in this blade file, we use highchart js and use their code.
resources/views/welcome.blade.php
Step 5: Create Dummy Records:
For creating dummy records, run the below command
php artisan tinker
User::factory()->count(30)->create()
Read also: Laravel 9 Dynamic Highcharts Example
Then you will see 30 records are created in your users table. Now you can check it. Hope it will be helpful for you.