Laravel 9 - Google Bar Chart

Touseef Afridi
28 Aug 24

Laravel 9 - Google Bar Chart

In this tutorial, we will discuss how to integrate Google Bar Chart into Laravel 9. Google Bar Chart is a tool from Google Charts that allows you to create customizable, interactive bar charts to visually represent data, offering options to display data in both horizontal and vertical bars with various customization features.


If you're a video person, feel free to skip the post and check out the video instead!


Quick Overview

In this tutorial, we demonstrated how to integrate Google Bar Charts into a Laravel project to visualize data dynamically by fetching data from a database and displaying it in a bar chart using Google Charts. We started by creating a fresh Laravel project, setting up a database, and configuring the connection. After generating a product model, controller, and migration, we added columns for product details and defined mass-assignable properties in the model. Next, we created a blade view to render the Google Bar Chart and populated it with product data using PHP. A route was added to display the data, and a method in the controller fetched product records and passed them to the view for chart rendering. Finally, we tested everything by running the Laravel server and accessing the chart in the browser.

Step # 1 : Create Fresh Laravel Project or use existing Project.

Two commands to create fresh Laravel project
Create a fresh Laravel project named barchart using the global Laravel installer command.
laravel new barchart
Or
If the Laravel installer is not globally installed, use Composer to create the project named barchart
composer create-project laravel/laravel --prefer-dist barchart

Step # 2 : Create a Database.

Create a new database named barchart in your database management tool (phpMyAdmin). Then, update the .env file in your Laravel project with the database connection details.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=barchart
DB_USERNAME="your database username"
DB_PASSWORD="your database password"

Step # 3 : Create Model, Controller & Migration.

We need a product model, controller, and migration to add data for testing the bar charts.
php artisan make:model Product -a

Step # 4 : Add Columns to the product table.

Update the posts table migration to add product_name and price columns, then run the migration.
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('product_name');
            $table->string('price');
            $table->timestamps();
        });
    }
Define product_name and price as fillable properties in the Post model to allow mass assignment. Access Post model and add protected $fillable columns in Post class.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
    use HasFactory;
    protected $fillable = [
     'product_name',
     'price',
    ];
}
Run the migration to update the posts table.
php artisan migrate
Since this is for testing purposes, I will insert data directly into the column using phpMyAdmin to display it in the bar chart, which is the main goal here. Alternatively, you can use Tinker or create a form to add products.

Step # 5 : Create a View.

Create a blade file named google-barchart.blade.php and paste the provided code to display the Google Bar Chart with product data.
<!Doctype html>
<html lang="en">
<head>
    <title>Laravel 9 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">
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
    <div style="margin-top: 20px;">
        <h1 style="text-align: center;">Laravel 9 Google Bar Chart</h1>
        <div class="container-fluid p-5">
            <div id="barchart" 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([
                ['Product Id', 'Price', 'Product Name'],
                @php
                foreach ($products as $product) {
                    echo "['" . $product->id . "', '" . $product->price . "', '" . $product->product_name . "'],";
                }
                @endphp
            ]);
            var options = {
                chart: {
                    title: 'Bar Graph',
                    subtitle: 'Sales Comparison',
                },
                bars: 'vertical'
            };
            var chart = new google.charts.Bar(document.getElementById('barchart'));
            chart.draw(data, google.charts.Bar.convertOptions(options));
        }
    </script>
</body>
</html>

Step # 6 : Setup route.

Add a route to display bar chart data.
Route::get('/results', 'App\Http\Controllers\ProductController@index');

Step # 7 : Create a method.

Access ProductController, import the Product class, and create an index method to fetch all products and pass them to the blade view.
use App\Models\Product;
class ProductController extends Controller
{
 public function index()
 {
 $products = Product::all();
 return view('google-barchart', ['products' => $producsts]);
 }
}

Step # 8 : It's time to test.

Run the Laravel development server.
php artisan server
Visit the URL: http://127.0.0.1:8000/results

Conclusion

By following these steps, you learned how to integrate Google Bar Charts into a Laravel application for data visualization. This approach allows you to present data in an interactive and visually appealing format. You can further extend this functionality by adding filters, dynamic data sources, or integrating other chart types for a more comprehensive data visualization experience.

Share this with friends!


"Give this post some love and slap that 💖 button as if it owes you money! 💸😄"
0

0 Comments

To engage in commentary, kindly proceed by logging in or registering