Laravel 7

How to Implement Google Charts in Laravel 7 App Example

Pinterest LinkedIn Tumblr

How to Implement Google Charts in Laravel 7 App Example

In this tutorial we will learn laravel 7 chart example from scratch. we will discuss about laravel 7 charts step by step everything about google chart.we will implement dynamic pie chart in laravel aslo we will utilize google chart api.

Google provides the different types of charts such as Bar chart, Line chart, Area chart, Pie chart and many more. Today, we will try to implement some chart with the dynamic data which will be retrieved through the MySQL database.

Step 1: Download laravel 8 project

 composer create-project --prefer-dist laravel/laravel laravel7google
 cd laravel7google

Step 2: Configure Your database from .env file


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=CronJob
DB_USERNAME=root
DB_PASSWORD=root@123

Step 3: Create Model and migration

php artisan make:model Employee -m

Step 4: Open your database/migrations/2020_10_08_163700_create_employees_table.php

<?php

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

class CreateEmployeesTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('employees', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('gender');
            $table->timestamps();
        });
    }

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

Step 5: Generate Seeder

php artisan make:seeder EmployeeSeeder

Open database seeder database/seeds/DatabaseSeeder.php

<?php
  
use Illuminate\Database\Seeder;
   
class DatabaseSeeder extends Seeder
{
    /**
     * Seed the application's database.
     *
     * @return void
     */
    public function run()
    {
        $this->call(EmployeeSeeder::class);
    }
}

And generate faker data inside of EmployeeSeeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use App\Models\Employee;
use Illuminate\Support\Facades\DB;
use Faker\Factory as Faker;

class EmployeeSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
   
    public function run(Faker $faker)
    {
	$faker = Faker::create();
        foreach (range(1,10) as $index) {
            DB::table('employees')->insert([
                'name'    =>   $faker->name,
                'gender'  =>   $faker->randomElements(['male', 'female'])[0],
            ]);
        }
    }    
}

Next, we need to run below the PHP artisan command to generate 10 fake rows in the Employee database table.

php artisan db:seed

Step 6: Route

Open routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;

Route::get('/', 'GoogleGraph@index');

Step 7: Make Controller

In this step first we will create Controller in our Laravel application. run the following command

php artisan make:controller GoogleGraph

Above command will make controller in app/Http/Controllers/GoogleGraphp.php now open to this controller and create index() method in it for fetch data from mysql table and convert into json string and lastly it will send that data to view file. For this process you can find source code below.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;
use App\Employee;


class GoogleGraph extends Controller
{
    function index()
    {

      $data = Employee::select(
        DB::raw('gender as gender'),
        DB::raw('count(*) as number'))
       ->groupBy('gender')
       ->get();

     $array[] = ['Gender', 'Number'];
     foreach($data as $key => $value)
     {
       $array[++$key] = [$value->gender, $value->number];
     }
     return view('google_pie_chart')->with('gender', json_encode($array));
    }
}

Step 8: Add view file

here, we need to create blade file and in this blade file we use Google Chart and use their code.This is our output which will display chart on web page in browser. In this file we have write javascript code for generate pie chart by using Google Chart API and data has been get from Laravel controller.

resources/views/google_pie_chart.blade.php

<!DOCTYPE html>
<html>
 <head>
  <title>Laravel 7 Google Chart</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" />
  
  <script type="text/javascript">
   var analytics = <?php echo $gender; ?>

   google.charts.load('current', {'packages':['corechart']});

   google.charts.setOnLoadCallback(drawChart);

   function drawChart()
   {
    var data = google.visualization.arrayToDataTable(analytics);
    var options = {
     title : 'Percentage of Male and Female Employee'
    };
    var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));
    chart.draw(data, options);
   }
  </script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Percentage of Male and Female Employee</h3>
   <div class="panel panel-default">
    <div class="panel-body" align="center">
     <div id="pie_chart" style="width:750px; height:450px;">
     </div>
    </div>
   </div>
   
  </div>
 </body>
</html>

Run Server:

php artisan server