Table of Contents
- Introduction
- Prerequisites
- Setting Up Laravel
- Creating a Database and Table
- Fetching Data from the Database
- Installing Google Charts Library
- Creating a Controller
- Creating a Route
- Creating a View
- Integrating Google Charts
- Conclusion
Introduction
In this tutorial, we’ll learn how to integrate Google Charts dynamically into a Laravel 11 application. Google Charts is a powerful, simple-to-use library that allows you to visualize data on your web applications. By the end of this tutorial, you’ll be able to create a chart that dynamically fetches and displays data from a database.
Prerequisites
Before we start, make sure you have the following:
- PHP >= 8.1
- Composer
- Laravel 11 installed
- Basic knowledge of Laravel and PHP
Setting Up Laravel
First, let’s set up a new Laravel project. Open your terminal and run:
composer create-project --prefer-dist laravel/laravel laravel-google-charts
Navigate to the project directory:
cd laravel-google-charts
Creating a Database and Table
Next, let’s create a database and a table to store the data we want to visualize. Open your .env
file and set up your database connection:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=google_charts_db
DB_USERNAME=root
DB_PASSWORD=
Now, create a migration file for our table:
php artisan make:migration create_sales_table
In the migration file (database/migrations/xxxx_xx_xx_xxxxxx_create_sales_table.php
), add the following code:
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration {
public function up(): void {
Schema::create('sales', function (Blueprint $table) {
$table->id();
$table->string('product_name');
$table->integer('quantity');
$table->timestamps();
});
}
public function down(): void {
Schema::dropIfExists('sales');
}
};
Run the migration to create the table:
php artisan migrate
Now, let’s seed the database with some sample data. Create a seeder file:
php artisan make:seeder SalesTableSeeder
In the seeder file (database/seeders/SalesTableSeeder.php
), add the following code:
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
class SalesTableSeeder extends Seeder {
public function run() {
DB::table('sales')->insert([
['product_name' => 'Product A', 'quantity' => 100],
['product_name' => 'Product B', 'quantity' => 150],
['product_name' => 'Product C', 'quantity' => 200],
]);
}
}
Run the seeder:
php artisan db:seed --class=SalesTableSeeder
Fetching Data from the Database
Now, let’s create a model for our sales
table. Run the following command:
php artisan make:model Sale
Installing Google Charts Library
Since Google Charts is a JavaScript library, we don’t need to install it using Composer or NPM. We’ll directly include it in our view.
Creating a Controller
Let’s create a controller that will fetch data from the database and pass it to the view:
php artisan make:controller ChartController
In the ChartController.php
file (app/Http/Controllers/ChartController.php
), add the following code:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Sale;
class ChartController extends Controller {
public function index() {
$sales = Sale::all();
$salesData = [];
foreach ($sales as $sale) {
$salesData[] = [$sale->product_name, $sale->quantity];
}
$salesData = json_encode($salesData);
return view('chart', compact('salesData'));
}
}
Creating a Route
Next, we need to create a route to display our chart. Open the web.php
file (routes/web.php
) and add the following route:
use App\Http\Controllers\ChartController;
Route::get('/chart', [ChartController::class, 'index']);
Creating a View
Now, let’s create a view that will display our chart. Create a new file named chart.blade.php
in the resources/views
directory and add the following code:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Google Charts</title>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Product Name', 'Quantity'],
@php
echo $salesData;
@endphp
]);
var options = {
title: 'Product Sales',
hAxis: {title: 'Product Name', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="chart_div" style="width: 100%; height: 500px;"></div>
</body>
</html>
Integrating Google Charts
The code above loads the Google Charts library and sets up a function to draw the chart using the data passed from the controller. The @php echo $salesData; @endphp
line outputs the JSON-encoded sales data.
Conclusion
Congratulations! You’ve successfully integrated Google Charts into your Laravel 11 application. You can now visualize data dynamically fetched from your database. This is a powerful way to enhance the user experience and present data in a more meaningful way.
Feel free to customize the chart options and data to fit your specific needs. Happy coding!
- Check our tools small Tools
- Check our tools website Word count