Laravel 10 and Google Line Chart Integration Tutorial

Share this Article
Reading Time: 6 minutes
161 Views

Inside this article we will see the concept i.e Laravel 10 and Google Line Chart Integration Tutorial. Article contains the classified information i.e Step-by-step guide for adding Google Line Chart in Laravel 10.

The tutorial covers the basics of creating a Line Chart using the Google Charts API and demonstrates how to implement it in a Laravel 10 application. The article provides code snippets and examples to make the integration process easy to understand and follow.

Read More: Step-by-Step CSV Data Seeding with Laravel 10 Tutorial

Let’s get started.

Laravel Installation

Open terminal and run this command to create a laravel project.

$ composer create-project laravel/laravel myblog

It will create a project folder with name myblog inside your local system.

To start the development server of laravel –

$ php artisan serve

URL: http://127.0.0.1:8000

Assuming laravel already installed inside your system.

Create Database & Connect

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

CREATE DATABASE laravel_app;

To connect database with application, Open .env file from application root. Search for DB_ and update your details.

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

Read More: Laravel 10 How To Integrate Line Chart Using HighChart Tutorial

Create Model & Migration

Open project into terminal and run this command to create model & migration file.

$ php artisan make:model Visitor -m

It will create two files –

  • Model – Visitor.php inside /app/Models folder
  • Migration file – 2023_02_18_123805_create_visitors_table.php inside /database/migrations folder.

Open Migration file and write this complete code into it.

<?php

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

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

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

Run Migration

Back to terminal and run this command.

$ php artisan migrate

It will create visitors table inside database.

Next,

Insert Application Test Data

Open application database and run this MySQL query to insert test data into visitors table.

--
-- Dumping data for table `visitors`
--

INSERT INTO `visitors` (`id`, `click`, `viewer`, `created_at`, `updated_at`) VALUES
(1, 25, 80, '2020-02-07 13:00:00', '2020-02-07 13:00:00'),
(2, 10, 45, '2021-02-11 13:00:00', '2021-02-11 13:00:00'),
(3, 18, 65, '2022-02-13 13:00:00', '2022-02-13 13:00:00'),
(4, 14, 57, '2023-02-21 13:00:00', '2023-02-21 13:00:00');

Right now, we have only these few rows of dummy data. You can take more rows in it. These data will help to draw graph between Total Click, Total Viewers according to Year wise.

You will see something like this after this test data insertion.

Create Controller Class & Method Setup

Next, we need to create a controller file.

$ php artisan make:controller GraphController

It will create a file GraphController.php inside /app/Http/Controllers folder.

Read More: Creating a Dynamic Pie Chart with Highcharts in Laravel 10

Open GraphController.php and write this complete code into it.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Visitor;
use Illuminate\Support\Facades\DB;

class GraphController extends Controller
{
    public function index()
    {
        $visitor = Visitor::select(
            DB::raw("year(created_at) as year"),
            DB::raw("SUM(click) as total_click"),
            DB::raw("SUM(viewer) 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));
    }
}

Create Template File

Go to /resources/views folder and create a file with name line-chart.blade.php

Open line-chart.blade.php and write this complete code into it.

<html>
  <head>

    <title>Laravel 10 and Google Line Chart Integration Tutorial - ONLINE WEB TUTOR</title>

    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <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>
  </head>
  <body>
    <h3 style="text-align: center;">Laravel 10 and Google Line Chart Integration Tutorial - ONLINE WEB TUTOR</h3>
    <div id="linechart" style="width: 900px; height: 500px"></div>
  </body>
</html>
      

Add Route

Open web.php file from /routes folder. Add this route into it.

//...

use App\Http\Controllers\GraphController;

//...

Route::get('line-chart', [GraphController::class, 'index']);

//...

Application Testing

Open project to terminal and type the command to start development server

$ php artisan serve

URL: http://127.0.0.1:8000/line-chart

Output

We hope this article helped you to learn Laravel 10 and Google Line Chart Integration Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.