In this tutorial, we will find out how to use dynamic char bar using google charts in laravel.



Step 1 :

 Install Laravel App

composer create-project --prefer-dist laravel/laravel blog



Step 2 : 

Setup Database Configuration

open ".env" file and change the database

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password



Step 3: 

Create Model,Migration and Factory

php artisan make:model Product Employee -fm

app/Employee.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    protected $guarded = [];
}


database/migrations/2020_06_23_120117_create_employees_table.php

Schema::create('employees', function (Blueprint $table) {
    $table->id();
    $table->string("name")->nullable();
    $table->string("department_id")->nullable();
    $table->string("salary")->nullable();
    $table->timestamps();
});

migrate to table using this command:

php artisan migrate

database/factories/EmployeeFactory.php

<?php

/** @var \Illuminate\Database\Eloquent\Factory $factory */

use App\Employee;
use Faker\Generator as Faker;

$factory->define(Employee::class, function (Faker $faker) {
    return [
        "name"          =>  $faker->word,
        "department"   =>   $faker->numberBetween(1,100),
        "salary"         =>  $faker->numberBetween(1, 100),
    ];
});
 

create some fake data by pasting it in your terminal

php artisan tinker
//then
factory(\App\Employee::class,100)->create()



Step 4 : 

Create Route

Route::get("barchart", "EmployeeController@get_all_employees");



Step 5 : 

Create Controller

php artisan make:controller EmployeeController

app/http/controller/EmployeeController.php

<?php

namespace App\Http\Controllers;

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

class EmployeeController extends Controller
{
    public function get_all_employees()
    {
       $employees = Employee::all();
       return view('employee',['employees' => $employees]);   
    }

}



Step 6:

Create Blade File

/resources/views/employee.blade.php

<!doctype html>
<html lang="en">
  <head>
    <title>Google Bar Chart</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
  <body>
    <h2 style="text-align: center;">Laravel Google Bar Charts Example Tutorial - Nicesnippets.com</h2>
    <div class="container-fluid p-5">
    <div id="barchart_material" style="width: 100%; height: 500px;"></div>
    </div>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>


    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">

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

      function drawChart() {
        var data = google.visualization.arrayToDataTable([
            ['Employee Id', 'Salary', 'Department'],

            @php
              foreach($employees as $employee) {
                  echo "['".$employee->id."', ".$employee->salary.", ".$employee->department_id."],";
              }
            @endphp
        ]);

        var options = {
          chart: {
            title: 'Bar Graph | Salary',
            subtitle: 'Salary, and Department: @php echo $employees[0]->created_at @endphp',
          },
          bars: 'vertical'
        };
        var chart = new google.charts.Bar(document.getElementById('barchart_material'));
        chart.draw(data, google.charts.Bar.convertOptions(options));
      }
    </script>

</body>
</html>


I hope this example helps you.