Bar Chart Example using Google Chart in Laravel 7

18169 views 1 year ago Laravel

Hello Artisan

Hope you are doing well. In this tutorial i am going to discuss about laravel charts. That in this tutorial i will show you how we can exhibit bar chart or how we can engender bar chart dynamically in laravel 7.

To do this laravel dynamic bar charts i will utilize google charts. Google Charts provides an impeccable way to visualize data on your website.Using this google charts i will show you how we can show our product data info in bar charts. It will be a simple demo tutorial on laravel bar charts.

I will just engender a simple product model and a product controller to engender this laravel google charts example. Then i will fetch product data from database and conclusively set in google bar chart function.

If you don't ken how to make laravel dynamic data chart or how to utilize google charts with laravel, don't worry. You are a right place. I will avail you to learn step by step how to utilize google charts to visualize data on your website in laravel.

Step 1: Download Laravel 7

In this step we need to download our fresh laravel app. So download it by the below command.

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

Step 2: Create Route

Now we need to create our route to create a function where from we fetch our data from database. Paste below code to web.php file.

routes/web.php

Route::get("barcharts", "[email protected]_all_products");

Step 3: Create Model and Factory

We need a product table to create dynamic laravel charts. Also we need factory to generate some fake dummy products. So create it using below command.

php artisan make:model Product -fm

Now open product model and set it like below

app/Product.php

namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
    protected $guarded = [];
}

After doing it we need to create our migration to migrate our database.

database/migrations/creates_products_table.php

Schema::create('products', function (Blueprint $table) {
    $table->id();
    $table->string("name")->nullable();
    $table->string("sku")->nullable();
    $table->string("description")->nullable();
    $table->string("price")->nullable();
    $table->integer("quantity");
    $table->integer("sales");
    $table->timestamps();
});

now run migrate command

php artisan migrate

Now we have to create our factory to generate some dummy products.

database/factories/ProductFactory.php

/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Product;
use Faker\Generator as Faker;
$factory->define(Product::class, function (Faker $faker) {
    return [
        "name"          =>  $faker->word,
        "sku"           =>  $faker->unique()->randomNumber,
        "description"   =>  \Str::random(20),
        "price"         =>  $faker->numberBetween(1000, 10000),
        "quantity"      =>  $faker->numberBetween(1,100),
        "sales"         =>  $faker->numberBetween(1,100)
    ];
});

Now open your terminal and paste it in your termial to create some fake data.

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

After running this command we will get 100 product in our products table.

Step 4: Create Controller

Now time to create product controller to write our get all product function to fetch products from database. So create it via below command.

php artisan make:controller ProductController

Now open it and paste this below code.

app/Http/Controllers/ProductController.php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ProductController extends Controller
{
    public function get_all_products()
    {
       $products = \App\Product::all();
       return view('product',['products' => $products]);   
    }
}

Step 5: Create Blade File

Now we have to create our product.blade.php to generate our products bar charts. So create it in your views folder.

resources/views/product.blade.php

<!doctype html>
<html lang="en">
  <head>
    <title>Google Bar Chart | LaravelCode</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>
    <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([
            ['Product Id', 'Sales', 'Quantity'],
            @php
              foreach($products as $product) {
                  echo "['".$product->id."', ".$product->sales.", ".$product->quantity."],";
              }
            @endphp
        ]);
        var options = {
          chart: {
            title: 'Bar Graph | Sales',
            subtitle: 'Sales, and Quantity: @php echo $products[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 you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]