How to Integrate & Dynamically Use Google Charts in Laravel 9

This is a comprehensive tutorial on implementing and using Google Chart dynamically in the Laravel application.

Integrating dynamic charts in Laravel is not that difficult, laravel mechanism lets you deal with Google charts easily. We will show you a laravel eight google chart example and shed light on how to use google charts in laravel.

Google charts js offer numerous robust charts such as Area Chart, Bar Chart, Pie Chart, Column Chart, and Geo Chart. However, you will learn about the laravel google line chart example in this tutorial.

I believe this tutorial will surely help through the example of Google line chart and help you flex your muscle in laravel web development and make your basic even stronger. Incredible, isn’t it?

Let me just give you a brief about what we are going to do in this article. The example of laravel google charts api example will begin with creating a new laravel application; in this game, Google charts JS API will help us catch the fish in the big pond.

So, let’s understand how to use the Google line chart in the laravel project without further ado. How to Quickly Integrate & Use Google Charts in Laravel dynamically.

Create Laravel Application

First thing first, head over to the command prompt or open the terminal window, enter the following command, and hit enter to install a new laravel application.

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

Move to the project root:

cd laravel-google-charts-example

Adding Database Details

Open the .env file and add the database name, username, and password collectively.

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

Head over to PHPMyAdmin and insert some dummy data using the SQL query through the SQL tab.

INSERT INTO `products` (`id`, `iphone_units`, `ipad_units`, `created_at`, `updated_at`) VALUES
(1, 300, 500, '2019-08-11 00:00:00', NULL),
(3, 750, 900, '2018-09-20 00:00:00', NULL),
(2, 375, 600, '2017-07-12 00:00:00', NULL),
(4, 270, 700, '2016-06-15 00:00:00', NULL),
(5, 350, 450, '2020-05-18 00:00:00', NULL),
(6, 1450, 2000, '2014-04-24 00:00:00', NULL),
(7, 1750, 1300, '2013-03-29 00:00:00', NULL),
(8, 1200, 500, '2011-02-19 00:00:00', NULL);

Create Model & Run Migration

You need to create a new table, name it “products”; this way, we can directly communicate with the database. So, run the following command to create a Product model.

php artisan make:model Product -m

Add the following values in database/migrations/timestamp_create_products_table.php for inserting in “products” table.

<?php

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

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

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

Open the app/Models/Product.php then register the given below values inside the $fillable array.

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
    protected $fillable = [
        'iphone_units',
        'ipad_units'
    ];
}

Run the database migration with the given below command:

php artisan migrate

Construct Controller

We have to generate a new controller using below command:

php artisan make:controller GoogleChartController

We will implement code for creating a line chart using Google chart js, so open the app/Http/Controllers/GoogleChartController.php and include the following code.

<?php

namespace App\Http\Controllers;

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

class GoogleChartController extends Controller
{
    public function googleChart()
    {
        $product = Product::select(
                        DB::raw("year(created_at) as year"),
                        DB::raw("SUM(ipad_units) as ipad_units"),
                        DB::raw("SUM(iphone_units) as iphone_units")) 
                    ->orderBy(DB::raw("YEAR(created_at)"))
                    ->groupBy(DB::raw("YEAR(created_at)"))
                    ->get();
  
        $response[] = ['Year', 'ipad_units', 'iphone_units'];
        foreach ($product as $key => $val) {
            $response[++$key] = [$val->year, (int)$val->ipad_units, (int)$val->iphone_units];
        }
  
        return view('home')
                ->with('product',json_encode($response));
    }
}

Define Route

The route is needed to invoke the view, so add the following code in the routes/web.php file.

<?php

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

/*
|--------------------------------------------------------------------------
| 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('home', [GoogleChartController::class, 'googleChart']);

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 lang="{{ str_replace('_', '-', app()->getLocale()) }}">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Laravel Google Chart Example</title>

</head>

<body class="antialiased">
    <h2>Laravel Line Chart Demo</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 product = <?php echo $product; ?>;
        console.log(product);
        google.charts.load('current', {
            'packages': ['corechart']
        });
        google.charts.setOnLoadCallback(lineChart);

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

</html>

Finally lets test out the Google Chart implementation in Laravel application:

php artisan serve

Open the following URL in the browser:

http://127.0.0.1:8000/home

Final output:

Dynamically Use Google Charts in Laravel
How to Quickly Integrate & Dynamically Use Google Charts in Laravel

Conclusion

We have completed Laravel Google Chart js tutorial with example, i hope you must have liked the learning paradigm, and this tutorial will be exorbitantly helpful for you.