How to Add Charts in Laravel using Chart.js

Here are the steps to add charts in Laravel:

Step 1: Create a Laravel Project

composer create-project laravel/laravel LaravelCharts --prefer-dist

Go to phpMyAdmin and create one database.

Switch to your editor, edit the .env file, and put your database credentials in it.

php artisan migrate

Step 2: Create one Controller file. 

We need to create one Controller file to manage the views and data. So go to the terminal and type the following command.

php artisan make:controller StockController --resource

Create one migration and model also by the following command.

php artisan make:model Stock -m

Go to that migration file, and we need to add new fields in the stocks table. To replace my code with your migration file.

<?php

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

class CreateStocksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stocks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('stockName');
            $table->integer('stockPrice');
            $table->integer('stockYear');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('stocks');
    }
}

Run the following command.

php artisan migrate

Go to the routes  >>  web.php file and put some routes regarding our application.

<?php

// web.php

Route::get('stock/add','StockController@create');
Route::post('stock/add','StockController@store');

Navigate to StockController and return a stock view from create() function.

<?php

// StockController.php

/**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        return view('Stock');
    }

Create one form to enter the data into the database.  

We are creating the Stock Market analysis chart. So We compare the Stock price against its period. So right now, we are creating one form.

<!-- Stock.blade.php -->

<!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/css/bootstrap-select.min.css">
    </head>
    <body>
        <div class="container">
          <br />
          <form action="{{url('stock/add')}}" method="post">
            {{csrf_field()}}
            <div class="form-group">
               <label for="stockName">Stock Name:</label>
               <input type="text" class="form-control" id="stockName" name="stockName">
             </div>
             <div class="form-group">
               <label for="stockPrice">Stock Price:</label>
               <input type="text" class="form-control" id="stockPrice" name="stockPrice">
             </div>
             <div class="form-group">
               <label for="stockPrice">Stock Year:</label>
               <select class="selectpicker" name="stockYear">
                  <option value="1991">1991</option>
                  <option value="1992">1992</option>
                  <option value="1993">1993</option>
                  <option value="1994">1994</option>
                  <option value="1995">1995</option>
                  <option value="1996">1996</option>
              </select>
            </div>
             <button type="submit" class="btn btn-primary">Submit</button>
          </form>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/bootstrap-select.min.js" charset="utf-8"></script>
    </body>
</html>

Now start the server by typing the following command.

php artisan serve

Go to this address: http://localhost:8000/stock/add

Step 3: Mass assignment exception.

To prevent the mass assignment exception, we must add protected the $fillable field and fill it with an array of columns to store the data.

Go to the model Stock.php and fill the $fillable array.

<?php

// Stock.php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Stock extends Model
{
    protected $fillable = ['stockName', 'stockPrice', 'stockYear'];
}

The next step is to store the values in the database.

<?php

// StockController.php

/**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $stock = new Stock([
          'stockName' => $request->get('stockName'),
          'stockPrice' => $request->get('stockPrice'),
          'stockYear' => $request->get('stockYear'),
        ]);
        $stock->save();

        return redirect('stocks');
    }

The next step would be to create an index view.

<!-- index.blade.php -->

<!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/css/bootstrap-select.min.css">
    </head>
    <body>
        <div class="container">
          <br />
          INDEX PAGE
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/bootstrap-select.min.js" charset="utf-8"></script>
    </body>
</html>

Also, we need to add a route for the index view.

// web.php

Route::get('stocks','StockController@index');

Return view of the index function.

// StockController.php

/**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return view('index');
    }

Step 4: Display the Bar Charts.

We need to display a Chart on the index page. I have used Bar Charts in this example. So if you want to learn more types, stay tuned to my website as I will put one-by-one types of charts.

Bar Charts

<!-- index.blade.php -->

<!doctype html>
<html lang="{{ config('app.locale') }}">
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>

        <!-- Fonts -->
        <link href="{{asset('css/app.css')}}" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/css/bootstrap-select.min.css">
    </head>
    <body>
      <div class="row">
       <div class="col-md-10 col-md-offset-1">
           <div class="panel panel-default">
               <div class="panel-heading"><b>Charts</b></div>
               <div class="panel-body">
                   <canvas id="canvas" height="280" width="600"></canvas>
               </div>
           </div>
       </div>
     </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.3/js/bootstrap-select.min.js" charset="utf-8"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.js" charset="utf-8"></script>
        <script>
        var url = "{{url('stock/chart')}}";
        var Years = new Array();
        var Labels = new Array();
        var Prices = new Array();
        $(document).ready(function(){
          $.get(url, function(response){
            response.forEach(function(data){
                Years.push(data.stockYear);
                Labels.push(data.stockName);
                Prices.push(data.stockPrice);
            });
            var ctx = document.getElementById("canvas").getContext('2d');
                var myChart = new Chart(ctx, {
                  type: 'bar',
                  data: {
                      labels:Years,
                      datasets: [{
                          label: 'Infosys Price',
                          data: Prices,
                          borderWidth: 1
                      }]
                  },
                  options: {
                      scales: {
                          yAxes: [{
                              ticks: {
                                  beginAtZero:true
                              }
                          }]
                      }
                  }
              });
          });
        });
        </script>
    </body>
</html>

Now, I have to Use the Ajax request to fetch the data from the database. So first, I need to define one route for that, and I am posting a routing code.

// web.php

<?php

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});

Route::get('stock/add','StockController@create');
Route::post('stock/add','StockController@store');

Route::get('stocks','StockController@index');
Route::get('stock/chart','StockController@chart');

We need to code the chart function of StockController. I have just created the sample chart of an Indian Stock Market Company called Infosys.

<?php

// StockController.php

  /**
     * Fetch the particular company details
     * @return json response
     */
      public function chart()
      {
        $result = \DB::table('stocks')
                    ->where('stockName','=','Infosys')
                    ->orderBy('stockYear', 'ASC')
                    ->get();
        return response()->json($result);
      }

Step 5: Try in the browser.

If you have included all the JS libraries ideally and have proper values in the database regarding charts, switch to the following URL.

http://localhost:8000/stocks

If you do not see anything, please go to this URL first.

http://localhost:8000/stock/add

Charts in Laravel

Add some stocks and their values in the database concerning years. Then come again the following route.

http://localhost:8000/stocks

How to add Charts in Laravel

Download Project on Github

That’s it.

11 thoughts on “How to Add Charts in Laravel using Chart.js”

  1. Hey, the tutorial was very helpfull and i say thank you for that, but when it comes time to display datas in the chart i get a response from the server which says that No properties and the fact is that the chart is empty.
    What can i do to fix it ? Thanks for your help. I hope to read you as soon as possible

    Reply

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.