For representing any data in a graphical way the chart can be used. There are lots of charts available in JavaScript. We can use any of the chart libraries. In this post, I will be showing you a quick guide to implement Google Charts in Laravel 7. Google provides the different types of charts such as Bar chart, Line chart, Area chart, Pie chart and many more. Today, I will try to implement some chart with the dynamic data which will be retrieved through the MySQL database. There are lots of differences in the chart. Some charts accept the JSON data, some chart accepts Array data. So, this will depend upon the types of charts.
Prerequisites
I will be starting with a new application in Laravel 7. Before creating the application, your system must be ready with the following configurations –
- PHP >= 7.2.5
- MySQL > 5
- Apache/Nginx Server
- VS Code Editor (Optional)
- Composer
Once you are ready, create the application in Laravel 7 for implementing the Google charts.
Laravel 7 RESTful APIs with Passport Authentication
Create a Project in Laravel 7 For Google Charts
Open the terminal and create a Laravel 7 project by using the composer.
composer create-project --prefer-dist laravel/laravel google-chart
The above command will start creating a new project. This will create a folder with the name google-chart. Then inside this folder, all the necessary files will be installed.
Once, the setup will be completed, let’s open it in the editor.
Create and Configure a new Database
For accessing the database, I am using the MySQL command prompt. Create a database there or if you have any existing database that contains any product or sales related data then you can use it.
CREATE DATABASE laravel7_chart_db;
For integrating the database with Laravel 7 project, change the database credentials inside the .env file as showing below.
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel7_chart_db
DB_USERNAME=root
DB_PASSWORD=root
Laravel 7 Upload Multiple Images with Image Validation
Create a Model and Migration
I will create a model and migration for the product. Actually, I will be
implementing the Google charts for the products. Hence, enter the below command in the terminal. It will create a model and migration file.
php artisan make:model Product --migration
Navigate the product migration file and paste the below code for the table schema.
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string("product_name")->nullable();
$table->string("sku")->nullable();
$table->string("description")->nullable();
$table->string("price")->nullable();
$table->integer("quantity");
$table->integer("sales");
$table->timestamps();
});
}
Here, the table schema is ready. Now, let’s migrate the table.
php artisan migrate
The tables will be migrated into the database after hitting the above command.
Add Fillable Data in Product Model
We will specify the fields inside the Model (Product.php). This will communicate with the database for the specified fields.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $filable = [
"product_name", "sku", "description", "price", "quantity", "sales"
];
}
Here, I have defined the fields name as same I have created inside the table.
Create Dummy Data Using Factory Class
In Laravel, you can create dummy records using a tinker class. But before using the tinker class, we will create a factory. The factory class will be associated with the model. Here, we have the Product model. So, we will create a ProductFactory and will assign the model
php artisan make:factory ProductFactory --model=Product
After hitting the above command, a factory file will be added inside the database folder.
In the next step, we will have to create the array of fields inside the ProductFactory.php file.
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
use App\Product;
use Faker\Generator as Faker;
use Illuminate\Support\Str;
$factory->define(Product::class, function (Faker $faker) {
return [
"product_name" => $faker->name,
"sku" => $faker->unique()->randomNumber,
"description" => Str::random(20),
"price" => $faker->numberBetween(1000, 10000),
"quantity" => $faker->numberBetween(1,100),
"sales" => $faker->numberBetween(1,100)
];
});
Create a tinker command to complete the factory. The tinker command will allow creating the number of dummy records in the table.
Just put the number of records that want to create. It will create the dummy records, so wait till it finishes the execution.
Create a Controller For Implementing Google Charts
For getting the data from the database, we need a controller. So, create a controller inside the project by artisan command.
php artisan make:controller ProductController
Here, controller has been created. Now, let’s add some code there.
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Product;
class ProductController extends Controller
{
public function prouductsListing() {
$products = Product::all();
return view("show-products", compact("products"));
}
}
In the above controller, I have created a function to get all the products from the products table. Also, it will return to a view named show-products with the products data.
Add Routes
For creating a route, just navigate to the routes folder. Here, we are creating the web route for the web application. That’s why we will need to define the route inside the web.php file.
Route::get("products", "ProductController@prouductsListing");
So, the route has been created and now, it’s time to create the view.
Create Views
Move to the resources/views and create a view with the name show-products.blade.php.
Add Google Chart
Now, for Google charts visit the Google Developers Then look at the bar charts and select any one.
I am choosing the material charts.
Below the material bar chart there will be the script. Just copy it now move to the project folder and inside the view just paste the code.
<!doctype html>
<html lang="en">
<head>
<title>Google Bar Chart | Programming Fields</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>
In the above snippet, I have fetched the product detail which are coming from the controller file. Then, inside the script code, I have iterate the loop so that all the product details can be fetched inside the Google bar chart.
In the options of google bar chart, I have changed the orientation from horizontal to vertical.
Save and run the application to see the result. The application will start running on the default port 8000. As a result, you can see the Google bar chart has been implemented successfully.
You can style the webpage by using some CSS as per your requirement. Actually, I am not focusing on the design part in this tutorial.
Implement the Google Pie Chart
Similarly, we can implement the Google pie chart. So, in the controller just add one more function.
public function pieChartListing() {
$products = Product::all();
return view("google-pie-chart", compact("products"));
}
Add one more route for the above function.
Route::get("pie-chart", "ProductController@pieChartListing");
Create an another view named google-pie-chart.blade.php and paste the below code.
<!doctype html>
<html lang="en">
<head>
<title>Google Pie Chart | Programming Fields</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 p-5">
<h5> Google Pie Chart | Programming Fields </h5>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</div>
<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', 'Sales', 'Quantity'],
@php
foreach($products as $product) {
echo "['".$product->product_name."', ".$product->sales.", ".$product->quantity."],";
}
@endphp
]);
var options = {
title: 'Product Details',
is3D: true,
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</body>
</html>
Again save and run the application. This time the URL will be
http://localhost:8000/pie-chart
So, you can see with the same data we have implemented the Google pie chart also.
You can convert the pie chart into 3D by just adding a single value in the option.
var options = {
title: 'Product Details',
is3D: true,
};
Conclusion
Google chart is easy to setup and implement with Laravel. It is optimized, you can use any chart as per your data. I have shown you the basic demonstration of using the Google charts. So, I hope this will be very helpful for you. If you stuck in the implementation of Google charts then please let me know.
Abhinav Mule says
Yes ,I am stuck ..
Umesh Rana says
Hello Abhinav, what kind of issue you are facing? Please share it.
Abhinav Mule says
I don’t understand how to show data in bar chart that i want ..It’s showing other thing ..