How to create chart in Laravel 6?

Laravel 6 , Laravel

Nicesnippets

766

05-12-2019


hii guys,

In this example,I will show you how to create chart in laravel 6 application. here we will use laravel chart library to create chart in laravel 6 application. we will use consoletvs/charts package for adding chart in laravel 6.

Laravel chart library support Chartjs, Highcharts, Fusioncharts, Echarts, Frappe and C3 libraries.

In this example we will create line chart using Chartjs library for new registered users.

Follow below step to create chart in your application :

Step 1: Install Laravel 6

you will create laravel 6 fresh application.

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

Step 2: Install Package

Here we will install package so run below command in your terminal :

composer require consoletvs/charts

Publish Assets

In this step we will publish the assets using the following command.

php artisan vendor:publish --tag=charts_config

Step 3: Create User Chart Class

Run below command to create user chart class .

php artisan make:chart UserChart ChartJs

app\Charts\UserChart.php

Your userchart.php file should be like below :

<?php

namespace App\Charts;

use ConsoleTVs\Charts\Classes\Chartjs\Chart;

class UserChart extends Chart

{

/**

* Initializes the chart.

*

* @return void

*/

public function __construct()

{

parent::__construct();

}

}

Step 4: Create Route

routes/web.php

Add chart route in web.php file.

Route::get('chart', 'ChartController@index');

Step 5: Create Controller

Type below command to create ChartController :

php artisan make:controller ChartController

Update controller file like as below :

app/Http/Controllers/ChartController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\User;

use App\Charts\UserChart;

class ChartController 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');

$chart = new UserChart;

$chart->labels(['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']);

$chart->dataset('New User Register Chart', 'line', $users)->options([

'fill' => 'true',

'borderColor' => '#51C1C0'

]);

return view('user', compact('chart'));

}

}

Step 6: Create Blade File

Put below code in user blade file :

resources/views/user.blade.php

<!DOCTYPE html>

<html>

<head>

<meta charset="utf-8">

<title>Laravel Chart</title>

</head>

<body>

<div style="width: 80%;margin: 0 auto;">

{!! $chart->container() !!}

</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" charset="utf-8"></script>

{!! $chart->script() !!}

</body>

</html>

</pre>

It will help you....