How To Add Charts in Laravel 5 using ChartJS

How To Add Charts in Laravel 5 using ChartJS is today’s main topic to discuss. In real time web application, we have to deal with charts. If you are working in the Finance Field, then Charts are like Oxygen. You can not think of any Analysis without Charts. That is why I am creating an example of how you can add Charts in Laravel 5 web application.

If you want to learn basic tutorial of Laravel 5.4 then check out my other tutorial  Laravel 5.4 Crud Example From Scratch

Note: I am using all JavaScript Libraries through CDN. So if you are taking this course then you definitely have Internet Connection.

Step: 1

Create one Laravel project by typing following command.

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

Go to phpMyAdmin and create one database.

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

php artisan migrate

Step: 2

We need to create one Controller file to manage the views and data. So go to the terminal and type 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 stocks table. 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 Stock Market analysis chart. So We compare the Stock price against its period. 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 following command.

php artisan serve

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

Step: 3

To prevent mass assignment exception, we need to add protected $fillable field and fill with an array of columns we need 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'];
}

Next step is to store the values in the database.

Read More
1 of 4
<?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');
    }

Next step would be to create 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

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 then 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 Use Ajax request to fetch the data from the database. So first I need to define one route for that, and I am posting routing code for that.

// 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 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

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 first this URL.

http://localhost:8000/stock/add

 

Charts in Laravel

Add some stocks and its 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 root of the project and run command “composer update
  3. Edit .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 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

Still Doubt?? Ask in a comment below. I am happy to help you.

You might also like More from author

Leave A Reply

Your email address will not be published.