Generate Charts And Graphs Using Laravel

 

Using charts and graph’s to represent the data is the best effective solution for any website especially when the site has large data.  The idea behind this blog is to help you guys to generate charts and graphs using laravel. Let’s have a quick look on how to set this up in laravel.

 

Install composer

 

First, We need to install composer, Composer is a package management tool for PHP. Laravel requires composer for installation.

 

You can download the composer by using this link https://getcomposer.org/download/

 

After the installation, you can use “composer” command to check whether the composer got installed or not.

 

Installing Laravel

Current stable version of laravel is laravel 5.6. Alongside, we can also install the laravel package in three different ways. From command prompt or using terminal or using GitHub

Execute this command to install laravel, composer global require “laravel/installer” and then create a project like below.

 

Laravel new <project_name>

 

or

we can also create a project using via composer,

 

composer create-project --prefer-dist laravel/laravel <project_name>

 

Directly clone from GitHub

 

From this link you can get the laravel application https://github.com/laravel/laravel/tree/master and after that we need to install composer by using the command composer install.

 

How to Set Up Laravel On Local Server

 

Run the below command in command prompt or terminal

 

PHP artisan serve

[\code]

 

After executing this command laravel will start working on local  server

On localhost port if you want to change the default port number instead of 8000 and you can use the below command to do it.

http://localhost:8000

 

[code]

php artisan serve --port <port_number>

Generating Charts And Graphs

Here we are using consoletvs package for generating charts. So for installation, first, we should change the path for our project using command prompt or terminal. Follow the below steps to install

Step 1:

First, we need to install ConsoleTVs/Charts composer package inside our laravel project.

composer require consoletvs/charts

Step 2:

After installing successfully , open app/config.php and add service provider.

In config/app.php
'providers' => [
....
ConsoleTVs\Charts\ChartsServiceProvider::class,
],
After the service provider we need to add alias
'aliases' => [
....
'Charts' => ConsoleTVs\Charts\Facades\Charts::class,
]

Step 3

We need to configure the database for an application. We can configure it in either .env file or config/database.php file.

Step 4

Now we should migrate the default table named "user". We can find the table in database/migration folder.

Step 5

In order to generate charts first, we must generate dummy records for demo in users table. For creating dummy records, we need to run the below command in command prompt or terminal.

php artisan tinker>>> factory(App\User::class, 20)->create();

The above command will create a set of 20 records. If we need to add more records, we can increase the count as much as we want. For example,

php artisan tinker>>> factory(App\User::class, 2000)->create();

Step 6

Creating controller

For creating controller we need to run below command in terminal or command prompt

 

Php artisan make controller:<controller_name>

 

Step 7

Adding the routes

 

We can also add the routes for navigating our application. You can find routes file inside the routes folder. Before 5.4 we can directly find the routes.php file itself, now its web.php. If you are using laravel 5.2 then you could find the routes.php file inside the app/http folder.

 

So inside web.php, we can give the path,

 

Route::get('create-chart/{type}','ChartController@makeChart');

 

Here type will be the parameter we are passing it which will focus to makeChart() function inside chartcontroller.

 

Related: Laravel API – How to Build REST API with Laravel 5.5 / Laravel 5.6

 

Step 8

 

Import charts to controller, On the namespace section add the below line,

 

Use charts;

 

Step 9

To create the charts add the below code into chartController, here i have created bar chart, pie, donut, line, area, geo  and if you want it more then similarly you can add as much as you want.

 

public function makeChart($type)
{
switch ($type) {
case 'bar':
$users = User::where(DB::raw("(DATE_FORMAT(created_at,'%Y'))"),date('Y'))
->get();

$chart = Charts::database($users, 'bar', 'highcharts')
->title("Monthly new Register Users")
->elementLabel("Total Users")
->dimensions(1000, 500)
->responsive(true)
->groupByMonth(date('Y'), true);
break;
case 'pie':
$chart = Charts::create('pie', 'highcharts')
->title('HDTuto.com Laravel Pie Chart')
->labels(['Codeigniter', 'Laravel', 'PHP'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'donut':
$chart = Charts::create('donut', 'highcharts')
->title('HDTuto.com Laravel Donut Chart')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'line':
$chart = Charts::create('line', 'highcharts')
->title('HDTuto.com Laravel Line Chart')
->elementLabel('HDTuto.com Laravel Line Chart Lable')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'area':
$chart = Charts::create('area', 'highcharts')
->title('HDTuto.com Laravel Area Chart')
->elementLabel('HDTuto.com Laravel Line Chart label')
->labels(['First', 'Second', 'Third'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
case 'geo':
$chart = Charts::create('geo', 'highcharts')
->title('HDTuto.com Laravel GEO Chart')
->elementLabel('HDTuto.com Laravel GEO Chart label')
->labels(['ES', 'FR', 'RU'])
->colors(['#3D3D3D', '#985689'])
->values([5,10,20])
->dimensions(1000,500)
->responsive(true);
break;
default:
# code...
break;
}
return view('chart', compact('chart'));
}

 

Related: Tips To Improve The Performance Of A Laravel Application

Step 10

Create a blade file. Blade is the view file used inside the laravel. You can add new blade file with any name with an extension of .blade.php. Now, create a blade file and upload this code.

Creating chart.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>My Charts</title>
{!! Charts::styles() !!}
</head>
<body>
<!-- Main Application (Can be VueJS or other JS framework) -->
<div class="app">
<center>
{!! $chart->html() !!}
</center>
</div>
<!-- End Of Main Application -->
{!! Charts::scripts() !!}
{!! $chart->script() !!}
</body>
</html>

 

Step 11

 

Use the php artisan serve command to run the laravel application in local server.

 

http://localhost:8000/create-chart/bar
http://localhost:8000/create-chart/pie
http://localhost:8000/create-chart/donut
http://localhost:8000/create-chart/line
http://localhost:8000/create-chart/area
http://localhost:8000/create-chart/geo

 

In the above example, we were creating a line chart, geo chart, bar chart, pie chart, donut chart, line chart, and area chart. We can also create gauge chart, progress bar chart, areaspline chart, scatter chart, percentage chart with help of consoletvs charts composer package.

 

Also, there are lot of jquery libraries also available which can help us to create other charts like amcharts, charts, highchairs, google, material, chartist, fusion charts, Morris, etc. Using this plugin, we can easily create all these charts and hopefully, we don’t need any jquery to run this plugin which could be an added advantage of this plugin.  Explore more blogs on our largest blog repository and in case if you're a newbie then don't forget to subscribe us to get the latest updates from diverse technologies. Do post us your valuable thoughts in the comment section.

 

For any queries reach us via info@agiratech.com.