Laravel 7|8 Highcharts Example: Using Highcharts in Laravel

Last updated on by Digamber
This tutorial demonstrates how to create charts in Laravel 7 with Highcharts. We will gradually look into the entire process of working with laravel 7 and highcharts with example.

Laravel 7 Highcharts Example

Charts are frequently used to make the better understanding of a large set of data and the relationships between parts of the data. Charts can be scanned swiftly and efficiently, then compare to raw data.

Highcharts is an excellent open-source chart library, and you can represent data in through many ways. Such as Pie Charts, Line Charts, Bar Charts, Area Charts etc. In this tutorial, we are going to focus on creating a line chart using Highcharts with laravel.

New Laravel Application Invocation

Ideally, we need a new laravel application to write down about using Highcharts in Laravel. You can ignore this process if you already have the laravel app installed.

Otherwise, execute the given below command to define an archetype of laravel 7 application.

composer create-project laravel/laravel laravel-highcharts-example --prefer-dist

The execution of the above command heralds app has installed, now without wasting too much time get inside the app.

cd laravel-highcharts-example

Link with Database

Tutorial’s this part heralds about making the consensus between database and laravel application. Well, who doesn’t want to play around with data?

I meant with fetching and storing the data, so insert your database details in .env file. Such as information consists of your database name, user name and password.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

Run the following command to migrate the default user to the database.

php artisan migrate

Create Fake Records

We need to create some dummy user records to display the data in graphical form using charts.

In general, you can do it with ease by just using the following tinker command.

php artisan tinker

>>> factory(App\User::class, 50)->create();
>>> exit

The spontaneous response we received with above action, You can authenticate it by checking your MySQL database.

Using Highcharts in Laravel

Create and Configure Route

Routes are the foundational building block of laravel application, this is the pillar that bears the responsibility of navigation from point A to B and vice versa.

Ordinarily, we have to show a simple chart with some data rendered from the database. So, add the following route in routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('chart', 'HighchartController@handleChart');

Setting Up Controller

To show the chart and data simultaneously, let’s execute the following command to create a controller without being reckless.

php artisan make:controller HighchartController

Insert the following piece of code in app/Http/Controllers/HighchartController.php file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;

class HighchartController extends Controller
{
    public function handleChart()
    {
        $userData = User::select(\DB::raw("COUNT(*) as count"))
                    ->whereYear('created_at', date('Y'))
                    ->groupBy(\DB::raw("Month(created_at)"))
                    ->pluck('count');
          
        return view('home', compact('userData'));
    }
}

Define Blade File

Please create a new blade view file in resources/view/home.blade.php, in here we will import and create charts to show the demo of HighCharts in Laravel 7.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <title>Laravel 7 Highcharts Demo</title>
</head>

<body>
    <h1>Highcharts in Laravel 7 Example</h1>
    <div id="container"></div>
</body>

<script src="https://code.highcharts.com/highcharts.js"></script>

<script type="text/javascript">
    var userData = <?php echo json_encode($userData)?>;

    Highcharts.chart('container', {
        title: {
            text: 'New User Growth, 2020'
        },
        subtitle: {
            text: 'Source: positronx.io'
        },
        xAxis: {
            categories: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September',
                'October', 'November', 'December'
            ]
        },
        yAxis: {
            title: {
                text: 'Number of New Users'
            }
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'middle'
        },
        plotOptions: {
            series: {
                allowPointSelect: true
            }
        },
        series: [{
            name: 'New Users',
            data: userData
        }],
        responsive: {
            rules: [{
                condition: {
                    maxWidth: 500
                },
                chartOptions: {
                    legend: {
                        layout: 'horizontal',
                        align: 'center',
                        verticalAlign: 'bottom'
                    }
                }
            }]
        }
    });

</script>

</html>

Here are the number of users increased month wise, we are showing it through graphical representation using HighCharts.

Laravel 7 Highcharts Example

The Bottom Line

Eventually, we have completed this tutorial. In this tutorial, we learned how to display data with Highcharts in Laravel. I hope this tutorial will help you build the better comprehension of working with charts.

You can download the complete code of this tutorial from GitHub. If found helpful, then share it with others. Have a good day!