Laravel 8 Dynamic Google Charts Integration Tutorial with Example

Last updated on by Digamber

In this tutorial, we’d like to introduce you to the simple and easy method to dynamically implement and use Google Chart js in Laravel 8 application from scratch.

Dynamic Google Charts Integration in Laravel

No matter how robust feature and rich data your application has, that means nothing if that doesn’t offer any value to your users. Consequently, the comprehensive notion always indicates displaying the data with utmost clarity to end-user. Also, user experience nitty-gritty also supports this argument.

Google Charts offer you the easy method to display data to users effectively; consequently, Google Chart js makes data representation task less complicated. Innumerable data can be displayed through the compendium of charts like Area Chart, Bar Chart, Pie Chart, Column Chart, and Geo Chart.

Fret not, if you are a novice developer who has a question about how to use google charts in Laravel 8 project, then I’ll show you cognize Laravel 8 Google chart example.

This tutorial gives you a facile example of dynamic Google Line Chart in Laravel 8 using Google charts JS API.

Let’s get started!

Install Laravel Project

Open the command prompt and execute the given below command to create a laravel application. Skip this step if the app is already installed.

composer create-project laravel/laravel --prefer-dist laravel-google-charts-demo

Get inside the project.

cd laravel-google-charts-demo

Add Database Credentials

You need to include the database credentials such as database name, username, and password in .env file.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=demo
DB_USERNAME=root
DB_PASSWORD=

To display dynamic records in Line Chart is only possible if we have some records in the database. So, run the SQL query through PHPMyAdmin to add fake records.

INSERT INTO `wildlife_populations` (`id`, `bears`, `dolphins`, `created_at`, `updated_at`) VALUES
(1, 1200, 1400, '2020-09-12 00:00:00', NULL),
(3, 1600, 1500, '2019-08-31 00:00:00', NULL),
(2, 1475, 1570, '2018-07-14 00:00:00', NULL),
(4, 1280, 1100, '2017-06-13 00:00:00', NULL),
(5, 1350, 1450, '2016-05-19 00:00:00', NULL),
(6, 2450, 1800, '2015-04-26 00:00:00', NULL),
(7, 1050, 1300, '2014-03-22 00:00:00', NULL),
(8, 1300, 1500, '2013-02-18 00:00:00', NULL);

Model and Migration

To display data into the line chart we require to create a “wildlife_population” table.

Execute the command to create a model.

php artisan make:model WildlifePopulation -m

Open database/migrations/timestamp_create_wildlife_populations_table.php file and include the following code.

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateWildlifePopulationsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('wildlife_populations', function (Blueprint $table) {
            $table->id();
            $table->integer('bears');
            $table->integer('dolphins');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('wildlife_populations');
    }
}

Add the following table properties in app/Models/WildlifePopulation.php file.

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class WildlifePopulation extends Model
{
    use HasFactory;
    protected $fillable = [
        'bears',
        'dolphins'
    ];
}

Execute the command to run the migration:

php artisan migrate

Setting Up Route

Route is required to access the chart view, open the routes/web.php file and add the given below code.

<?php

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

/*
|--------------------------------------------------------------------------
| 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('line-chart', [ChartController::class, 'showChart']);

Generate and Configure Controller

For displaying the data we need controller it will fetch the data from the database and show in Google chart.

Generate controller using below command:

php artisan make:controller ChartController

Add the following code in app/Http/Controllers/ChartController.php file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\WildlifePopulation;
use DB;

class ChartController extends Controller
{
    public function showChart()
    {
        $population = WildlifePopulation::select(
                        DB::raw("year(created_at) as year"),
                        DB::raw("SUM(bears) as bears"),
                        DB::raw("SUM(dolphins) as dolphins")) 
                    ->orderBy(DB::raw("YEAR(created_at)"))
                    ->groupBy(DB::raw("YEAR(created_at)"))
                    ->get();
  
        $res[] = ['Year', 'bears', 'dolphins'];
        foreach ($population as $key => $val) {
            $res[++$key] = [$val->year, (int)$val->bears, (int)$val->dolphins];
        }
  
        return view('line-chart')
            ->with('population', json_encode($res));
    }
}

Show Google Line Chart in View

Apparently, we have reached the final step. In this step, we have to generate a home.blade.php file and implied throughly the following code to evoke the view and show the line chart example in the Laravel application.

Add the code in the resources/view/home.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <title>Laravel Google Chart Implementation Example</title>
</head>

<body class="antialiased">
    <h2>Integrating Line Chart in Laravel</h2>
    <div id="linechart" style="width: 1000px; height: 500px"></div>


    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
        var population = <?php echo $population; ?>;
        console.log(population);
        google.charts.load('current', {
            'packages': ['corechart']
        });
        google.charts.setOnLoadCallback(lineChart);

        function lineChart() {
            var data = google.visualization.arrayToDataTable(population);
            var options = {
                title: 'Wildlife Population',
                curveType: 'function',
                legend: {
                    position: 'bottom'
                }
            };
            var chart = new google.visualization.LineChart(document.getElementById('linechart'));
            chart.draw(data, options);
        }        
    </script>
</body>

</html>

Consequently, check the google chart implementation in Laravel project:

php artisan serve

On this URL you can open the line chart view:

http://127.0.0.1:8000/line-chart

The Bottom Line

We have seen how easy it is to integrate Google Charts in Laravel 8 application dynamically. However, we have implemented the line chart by following the same pattern; you can try your hands on other charts as well.