Laravel Dynamic Google Charts Integration Tutorial with Example

Throughout Laravel Dynamic Google Charts Integration Example Tutorial, we are going to share simple and easy way to dynamically implement and use Google Chart js in Laravel 9 application from scratch. You can create google chart in laravel 5, laravel 6, laravel 7, laravel 8 and laravel 9 application.

Google Charts offer you the easy method to display data to users effectively; consequently, Google Chart js makes data representation task less complicated. This tutorial gives you a facile example of dynamic Google Line Chart in Laravel 9 using Google charts JS API.

Google charts js provide several other charts like bar chart, Area chart, Column Chart, Pie Chart, GEO Chart etc. In this post we will use line chart with good graphical way. This tutorial gives you a facile example of dynamic Google Line Chart in Laravel using Google charts JS API.

Google Line Chart Example in Laravel

Follow the following steps to implement and use google chart in your laravel application to show the stats;

  • Step 1: Install Laravel App
  • Step 2: Connect App to Database
  • Step 3: Create Model & Migration
  • Step 5: Make Routes
  • Step 6: Create and Configure Controller
  • Step 7: Create Blade file
  • Step 8: Generate Dummy Records for Test

Install Laravel App

First we will install a new laravel app using the given below command. Skip this step if the app is already installed.

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

Get inside the project.

cd laravel-google-charts

Connect Database to App

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=

Create Model and Migration

Execute the command to create a model and migration file.

php artisan make:model Visitor -m

Open database\migrations\2022_03_04_025147_create_visitors_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 CreateVisitorsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('visitors', function (Blueprint $table) {
            $table->id();
            $table->string('viewers');
            $table->string('clicks');
            $table->timestamps();
        });
    }

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

Add the following table properties in app\Models\Visitor.php file.

<?php

namespace App\Models;

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

class Visitor extends Model
{
    use HasFactory;
    protected $fillable = [
        'viewers', 'clicks'
    ];
}

Execute the command to run the migration:

php artisan migrate

Make 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;

Route::get('line-chart', [ChartController::class, 'showChart']);

Create 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\Visitor;
use DB;
class ChartController extends Controller
{
    public function showChart()
    {
        $visitor = Visitor::select(
                        DB::raw("year(created_at) as year"),
                        DB::raw("SUM(clicks) as total_click"),
                        DB::raw("SUM(viewers) as total_viewer")
                     )
                    ->orderBy(DB::raw("YEAR(created_at)"))
                    ->groupBy(DB::raw("YEAR(created_at)"))
                    ->get();

        $result[] = ['Year','Click','Viewer'];

        foreach ($visitor as $key => $value) {
            $result[++$key] = [$value->year, (int)$value->total_click, (int)$value->total_viewer];
        }

        return view('line-chart')
                ->with('visitor',json_encode($result));
    }
}

Show Google Line Chart in Blade File

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/line-chart.blade.php file.

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  </head>
  <body>
    <h1>Laravel Google Chart Example</h1>
    <div id="linechart" style="width: 900px; height: 500px"></div>

    <script type="text/javascript">
      var visitor = <?php echo $visitor; ?>;
      console.log(visitor);
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable(visitor);
        var options = {
          title: 'Site Visitor Line Chart',
          curveType: 'function',
          legend: { position: 'bottom' }
        };
        var chart = new google.visualization.LineChart(document.getElementById('linechart'));
        chart.draw(data, options);
      }
    </script>
  </body>
</html>

Step 7: Generate Dummy Records for Testing

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 `visitors` (`id`, `viewers`, `clicks`, `created_at`, `updated_at`) VALUES
(1, 1800, 200, '2020-09-12 00:00:00', '2020-09-12 00:00:00'),
(2, 1500, 100, '2020-09-12 00:00:00', '2020-09-12 00:00:00'),
(3, 1200, 50, '2020-09-12 00:00:00', '2020-09-12 00:00:00'),
(4, 1600, 150, '2019-08-31 00:00:00', '2019-08-31 00:00:00'),
(5, 1475, 154, '2018-07-14 00:00:00', '2018-07-14 00:00:00'),
(6, 1280, 105, '2017-06-13 00:00:00', '2017-06-13 00:00:00'),
(7, 1350, 140, '2016-05-19 00:00:00', '2016-05-19 00:00:00'),
(8, 2450, 100, '2015-04-26 00:00:00', '2015-04-26 00:00:00');

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

We have seen how easy it is to integrate Google Charts in Laravel 9 application dynamically. I hope its works for you.

Leave a Comment