Laravel 11 Dynamic Google Charts Integration Tutorial

By Hardik Savani October 9, 2024 Category : Laravel

This tutorial demonstrates how to create charts in Laravel 11 with Google Chart Library. We will gradually look into the entire process of working with laravel 11 and google chart with examples.

Google Charts is a web-based charting tool built on the Google Visualization API. It allows users to build a variety of charts, including line graphs, bar charts, area charts, scatter plots, pie charts, and more. The charts are highly customizable and can be integrated into websites and applications with ease.

In this example, we will create some dummy user records and then display a line chart with all months of the current year. So let's follow the below steps and add a chart to your Laravel 11 apps.

laravel 11 google chart js

Step for How to Create Chart using Google JS in Laravel 11?

  • Step 1: Install Laravel 11
  • Step 2: Create Route
  • Step 3: Create Controller
  • Step 4: Create Blade File
  • Step 5: Create Dummy Records
  • Run Laravel App

Step 1: Install Laravel 11

This step is not required; however, if you have not created the Laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Create Route

First of all, we will create a simple route for creating a simple line chart. So let's add simple routes as below:

routes/web.php

<?php
  
use Illuminate\Support\Facades\Route;
  
use App\Http\Controllers\GoogleChartController;
  
Route::get('chart', [GoogleChartController::class, 'index']);

Step 3: Create Controller

Here, we will create a new controller named GoogleChartController. So let's add the code below to that controller file.

app/Http/Controllers/GoogleChartController.php

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DB;
use Illuminate\View\View;
  
class GoogleChartController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(): View
    {
        $users = User::select(DB::raw("COUNT(*) as count"), DB::raw("MONTHNAME(created_at) as month_name"))
                    ->whereYear('created_at', date('Y'))
                    ->groupBy(DB::raw("Month(created_at)"))
                    ->pluck('count', 'month_name');
            
        return view('chart', compact('users'));
    }
}

Step 4: Create Blade File

here, we need to create blade file and in this blade file we use google js and use their code.

resources/views/chart.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Google Chart Example - ItSolutionStuff.com</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" crossorigin="anonymous">
</head>
     
<body>
    <div class="container">
        <div class="card mt-5">
            <h3 class="card-header p-3">Laravel 11 Google Chart Example - ItSolutionStuff.com</h3>
            <div class="card-body"> 
                <div id="google-line-chart" style="height: 500px"></div>
            </div>
        </div>
    </div>
</body>
  
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
  
    google.charts.load('current', {'packages':['corechart']});
    google.charts.setOnLoadCallback(drawChart);
  
    function drawChart() {
  
        var data = google.visualization.arrayToDataTable([
            ['Month Name', 'Register Users Count'],
      
                @php
                    foreach($users as $key => $value) {
                        echo "['".$key."', ".$value."],";
                    }
                @endphp
        ]);
      
        var options = {
          title: 'Register Users Month Wise',
          curveType: 'function',
          legend: { position: 'bottom' }
        };
  
        var chart = new google.visualization.LineChart(document.getElementById('google-line-chart'));
  
        chart.draw(data, options);
    }

</script>
</html>

Step 5: Create Dummy Records:

Here, we need to add some dummy records on users table as monthly wise.

you can create dummy records using laravel tinker command as bellow:

php artisan tinker

User::factory()->count(30)->create()

You need to create users on each month with created date as like bellow screen shot:

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/chart

Output:

Output:

I hope it can help you...

Shares