How to show Line Chart by using Google Charts API in Laravel

Today now in this post i will show you How to show Line Chart by using Google Charts API in Laravel? Now in a days, Google have been a several popular API as like map, chart, analytics etc. In Google charts JS API is also a very popular and it is also very pretty and simple to integrate with our any application or projects. Now in this post, i am going to give you an example of Google line chart, How we can use Google line chart in our any laravel application.

We know Google charts js is provide us several other charts as like bar chart, Area chart, Column Chart, Pie Chart, GEO Chart etc. Now in this post i will use the line chart also with good graphical way.

Step 1: Add Table and Data

we need to create a new table as “visitor” on that way we will get the data from this table, we can use our own table but this is for an example. we need to create model with migration for the visitor table by using Laravel php artisan command, so first need to fire bellow command:

php artisan make:model Visitor

After using this command we will find one new file in the following path database/migrations and we have to put the bellow code in our migration file for create the visitor table.

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateVisitorTable extends Migration
{
    public function up()
    {
        Schema::create('visitor', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('click');
            $table->integer('viewer');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::drop("visitor");
    }
}

Ok, now we can add few records .

Step 2: Add Route

Now in this is step we have to add a new route for generate the view. so need to open our web.php file in location  routes/web.php file and then add following route.

Route::get('google-line-chart', 'HomeController@googleLineChart');
Step 3: Create Controller

If we haven’t HomeController then we need to create a new controller as HomeController in this path  app/Http/Controllers/HomeController.php by using bellow command.

php artisan make:controller HomeController

Make sure we should have an visitor table with the some data. This controller will be manage all data and chart data and can view file, so need to put bellow content in controller file:

app/Http/Controllers/HomeController.php

namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
use DB;


class HomeController extends Controller
{
    public function googleLineChart()
    {
        $visitor = DB::table('visitor')
                    ->select(
                        DB::raw("year(created_at) as year"),
                        DB::raw("SUM(click) as total_click"),
                        DB::raw("SUM(viewer) as total_viewer")) 
                    ->orderBy("created_at")
                    ->groupBy(DB::raw("year(created_at)"))
                    ->get();

        $result[] = ['Year','Click','Viewer'];
        foreach ($visitor as $key => $value) {
            $result[++$key] = [$value->year, (int)$value->total_click, (int)$value->total_viewer];
        }

        return view('google-line-chart')
                ->with('visitor',json_encode($result));
    }

}
Step 4: Create View File

Now we are in last step, we need to create a view file as “googlechart.blade.php” for generate the view chart, so need to create googlechart file and put the bellow code:

resources/view/googlechart.blade.php

<html>
  <head>
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
    <script type="text/javascript">
      var visitor = <?php echo $visitor; ?>;
      console.log(visitor);
      google.charts.load('current', {'packages':['corechart']});
      google.charts.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = google.visualization.arrayToDataTable(visitor);
        var options = {
          title: 'Site Visitor Line Chart',
          curveType: 'function',
          legend: { position: 'bottom' }
        };
        var chart = new google.visualization.LineChart(document.getElementById('linechart'));
        chart.draw(data, options);
      }
    </script>
  </head>
  <body>
    <div id="linechart" style="width: 900px; height: 500px"></div>
  </body>
</html>

Read Also : Laravel 8 Mobile Number Verification Tutorial

Thanks for read. I hope it help you. For more you can follow us on facebook

close

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →