Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Laravel 11 Google Pie Chart Tutorial

Last Updated on April 23, 2024 by

In Laravel 11, the Google Charts JS library allows users to create pie charts to represent numerical proportions and present data in it by slices.

Let’s start creating a pie chart and retrieving data from a data source and displaying it in it using google charts:

Step 1 – Create Controller

controller named ChartController by using the following command:

php artisan make:controller ChartController

In ChartController.php file, add methods to fetch and pass the data on pie chart view:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class ChartController extends Controller
{
    public function index()
    {
        // Fetch data for the pie chart (replace this with your actual data retrieval logic)
        $data = [
            ['Task', 'Hours per Day'],
            ['Work', 11],
            ['Eat', 2],
            ['Commute', 2],
            ['Watch TV', 2],
            ['Sleep', 7]
        ];

        return view('pie-chart', compact('data'));
    }
}

Step 2 – Create Route

In routes/web.php, define a route to handle the data retrieval requests for your chart:

use App\Http\Controllers\ChartController;

Route::get('/chart', [ChartController::class, 'index']);

Step 3 – Create View

Create pie-chart.blade.php file in resources/views folder to render data into PIE CHART on blade view file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Laravel 11 Google Pie Chart Example - itcodstuff.com</title>
    <!-- Load Google Charts API -->
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
</head>
<body>
    <div id="pie_chart"></div>
</body>
</html>

Step 4 – Add Google Chart Library in View

In your Blade view file, add the Google Charts API:

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

Step 5 – Create PIE Chart and Display Data

In your Blade view file, render the pie chart using Google Charts API:

    <script>
        google.charts.load('current', {'packages':['corechart']});
        google.charts.setOnLoadCallback(drawChart);

        function drawChart() {
            var data = google.visualization.arrayToDataTable(@json($data));

            var options = {
                title: 'My Daily Activities'
            };

            var chart = new google.visualization.PieChart(document.getElementById('pie_chart'));

            chart.draw(data, options);
        }
    </script>

Step 6 – Test

Run application using artisan command:

php artisan serve

Hit http://localhost:8000/chart url on browser for testing.

Leave a Comment