Laravel 10 How To Use Google Bar Chart Example Tutorial

Reading Time: 6 minutes
505 Views

Google Bar Charts are an excellent tool for visualising data in web applications, particularly for comparing data across multiple categories or groups. To generate dynamic and interactive bar charts, Laravel, a sophisticated PHP framework, can be easily linked with Google Charts.

We will walk you through the process of using Google Bar Charts in Laravel 10, allowing you to present data in an educational and visually appealing manner.

Throughout this article, we’ll look at how to set up a Laravel project, integrate Google Charts, and create dynamic bar charts that can display data in real time.

Read More: Laravel 10 How To Use Google Pie Chart Example 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

Setup Model & Migration

Open project into terminal and run this command,

php artisan make:model Order -m

It will create two files,

  • Model – Order.php inside /app/Models folder
  • Migration file – xxx_create_orders_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(): void
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->id();
            $table->string("product_name")->nullable();
            $table->string("product_id")->nullable();
            $table->string("price")->nullable();
            $table->timestamps();
        });
    }

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

Run Migration

Next, you need to migrate migration files,

php artisan migrate

This command will create tables inside database.

Read More: Laravel 10 Create a Dynamic Line Chart Using HighChart

It will create orders table in database.

Next,

Prepare Dummy Data for Graph

You need to copy the given mysql query and run into sql tab of phpmyadmin. This will give us a set of data,

--
-- Dumping data for table `orders`
--

INSERT INTO `orders` (`id`, `product_name`, `product_id`, `price`, `created_at`, `updated_at`) VALUES
(1, 'Product 1', '5483TY', '120', '2023-02-06 18:30:00', NULL),
(2, 'Product 2', '45TRGF', '523', '2023-02-08 18:30:00', NULL),
(3, 'Product 3', 'FDFG5656', '236', '2023-02-11 18:30:00', NULL),
(4, 'Product 4', 'FDGT677', '450', '2023-02-13 18:30:00', NULL);

Right now, you have only these few rows of dummy data. But you can take more rows in it. These data will help to draw graph between Product and Price according to Order ID.

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

Create Data Controller

Next, you need to create a controller class,

php artisan make:controller GraphController

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

Open file and write this complete code into it,

<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\View\View;

class GraphController extends Controller
{
    public function index(): View
    {
        $orders = Order::all();
      
        return view('google-bar-chart', ['orders' => $orders]);
    }
}

Create Blade Template File

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

Open file and write this complete code into it,

<!doctype html>
<html lang="en">

<head>

    <title>Laravel 10 and Google Bar Chart Integration Tutorial</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">
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

</head>

<body>
    <div style="margin-top: 20px;">
        <h4 style="text-align: center;">Laravel 10 and Google Bar Chart Integration Tutorial</h4>
        <div class="container-fluid p-5">
            <div id="barchart_material" style="width: 100%; height: 500px;"></div>
        </div>
    </div>

    <script type="text/javascript">
        google.charts.load('current', {
            'packages': ['bar']
        });
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = google.visualization.arrayToDataTable([
                ['Order Id', 'Price', 'Product Name'],

                @php
                    foreach ($orders as $order) {
                        echo "['" . $order->id . "', '" . $order->price . "', '" . $order->product_name . "'],";
                    }
                @endphp
            ]);

            var options = {
                chart: {
                    title: 'Bar Graph | Price',
                    subtitle: 'Price, and Product Name: @php echo $orders[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>

Read More: Laravel 10 Create a Dynamic Pie Chart with Highcharts

Add Route

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

//...

use App\Http\Controllers\GraphController;

//...

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

//...

Application Testing

Run this command into project terminal to start development server,

php artisan serve

URL: http://127.0.0.1:8000/google-bar-chart

Output

That’s it.

We hope this article helped you to learn about Laravel 10 How To Use Google Bar Chart Example Tutorial in a very detailed way.

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.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more