How to Add Charts in Laravel 9 using Chart.js

11
1111
Charts in Laravel 5.4

Laravel chart.js minimal API to create modern and robust charts out of a few lines of PHP code. For example, we can create a line chart, bar chart, and pie chart using charts in Laravel.

I am using all JavaScript Libraries through CDN. So if you are taking this post, then you definitely have an Internet Connection. If you want to learn the basic tutorial of Laravel, then check out my other tutorial  Laravel Crud Example From Scratch.

Add Charts in Laravel 9

Laravel charts is a third-party charting library for laravel, and it can generate unlimited combinations of charts out of the box. This is because the Chart’s API is designed to be extensible and customizable, allowing any option in the JavaScript library to be quickly used without effort.

Let’s implement charts in Laravel step by step.

Step 1: Make one Laravel Project.

Create one Laravel project by typing the following command.

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

Go to phpMyAdmin and create one database.

Switch to your editor and 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 need to 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.

Now, 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 with my website as I will put one by one type of chart.

Bar Charts in Laravel

<!-- 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 perfectly and also you have proper values in the database regarding charts, then switch to the following URL

http://localhost:8000/stocks

If you do not see anything, then 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 following route.

http://localhost:8000/stocks

How to add Charts in Laravel

Download Project on Github

Steps to use Github code:

  1. Clone the repo in your local.
  2. Go to the root of the project and run the command “composer update.
  3. Edit the .env file and use your MySQL database credentials.
  4. I have used “Infosys” company, so if you want to use this chart, then either use my database as I am also putting the stocks.sql file in the root of the project on GitHub, or you need to modify that fetching data query to use your item or company whatever you want.
  5. Now, we need to bootstrap the Laravel server, so run “php artisan serve.
  6. If you are using my database, then directly go to the following URL:  http://localhost:8000/stocks
  7. If not, then now go to this URL: http://localhost:8000/stock/add
  8. Now add the particular company’s stock
  9. Again go to this URL: http://localhost:8000/stocks.

See also

Laravel Vue chart

Laravel Geo chart

React chart

11 Comments

  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

Leave A Reply

Please enter your comment!
Please enter your name here

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