AppDividend
Latest Code Tutorials

Creating charts with Laravel and Vue js Chart js Tutorial With Example

6,571

Get real time updates directly on you device, subscribe now.

Creating charts with Laravel and Vue js Chart js Tutorial Example is today’s topic. For this topic, we will use two web technologies. Laravel as a backend and Vue.js as a Frontend component. We will insert the data from vue component and display the data in the form of Charts. For charts, we will use a chartjs library. We use vue-chartjs as a wrapper for chart.js. Interactive charts can provide a neat way to visualize your data. It is comfortable and beautiful charts with Chart.js and Vue.js. Accessible for both beginners and pros; Simple to use, easy to extend; With the full power of chart.js.

Laravel and Vue js Chart js Tutorial

First of all, as usual, we will start out the tutorial by downloading the Latest Laravel version, and at the time of this example, Laravel 5.6 is latest so let us grab that.

Step 1: Install and configure Laravel 5.6

Hit the following command in your terminal.

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

Now laravel mix is configured for us out of the box, but we can not access it because we need to install the dependencies. So let us do that. Type the following command to install vue js dependencies.

npm install

After that, go to the webpack.mix.js file in the root folder.

// webpack.mix.js

let mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

The webpack.mix.js file compiles the es6 code and vue template compiler code into vanilla js, and we just need to include that generated js file into our project. If you are new to laravel mix, then check out my below article. It will help you to understand.

Now, the next thing is to go to the terminal and type the following command to watch our js and sass files for compilation. So, when we change the vue.js code, it automatically recompiles it, so we do not manually do compilation every time.

npm run dev

Also, we need to configure the database in the .env file. Next step is to create routes to add and display the data. We are building a simple application, which combines the details of the coin. It contains name, price and year.

Step 2: Make a vue.js component that displays form.

First, we need to change the welcome.blade.php file and add the id attribute to the main div so that we can bind the vue instance to our Laravel 5.6 application.

<<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Add Coin Details</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link href="{{ asset('css/app.css') }}" rel="stylesheet" />
</head>
<body>
   <div class="container" id="app"></div>
   <script>
         window.Laravel = <?php echo json_encode([
             'csrfToken' => csrf_token(),
          ]); ?>
   </script>
   <script src="{{ asset('js/app.js') }}" type="text/javascript"></script>
</body>
</html>

Next step is to create a form component inside resources  >>  assets  >>  js  >>  components folder called AddCoin.vue.

// AddComponent.vue

<template>
   <div class="col-md-8">
            <div class="card card-default">
                <div class="card-header">Add Coin</div>

                <div class="card-body">
                    <form @submit.prevent="addCoin">
                        <div class="form-group row">
                            <label for="name" class="col-sm-4 col-form-label text-md-right">Name</label>
                            <div class="col-md-6">
                                <input id="email" type="text" class="form-control" v-model="coin.name" required autofocus>
                            </div>
                        </div>

                        <div class="form-group row">
                            <label for="year" class="col-md-4 col-form-label text-md-right">Year</label>
                            <div class="col-md-6">
                                <input type="text" class="form-control" v-model="coin.year"  required>
                            </div>
                        </div>

                         <div class="form-group row">
                            <label for="year" class="col-md-4 col-form-label text-md-right">Price</label>
                            <div class="col-md-6">
                                <input type="text" class="form-control" v-model="coin.price"  required>
                            </div>
                        </div>

                        <div class="form-group row mb-0">
                            <div class="col-md-8 offset-md-4">
                                <button class="btn btn-primary">
                                    Add
                                </button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
</template>

<script>
   export default {
      data() {
         return {
            coin: {}
         }
      },
      methods: {
         addCoin() {
            alert('submitted');
         }
      }
   }
</script>

Okay, so we have created the component, now we need to include this component inside resources  >>  assets  >>  js  >>  app.js file.

// app.js

require('./bootstrap');

window.Vue = require('vue');

Vue.component('coin-add-component', require('./components/AddComponent.vue'));

const app = new Vue({
    el: '#app'
});

Finally, include that component inside welcome.blade.php file.

<div class="container" id="app">
   <coin-add-component></coin-add-component>
</div>

Your web.php file looks like this.

// web.php

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

Now, start the Laravel development server.

php artisan serve

Go to the http://localhost:8000.

Vue.js Chart.js Example Tutorial

 

Step 3: Create controller, model and migration files.

Type the below command to generate model and migration files.

 php artisan make:model Coin -m
 php artisan make:controller CoinController

It generates model, migration and controller file. In the controller file, write the store function to save the details of the coins. Now create the schema for our coins table. So go to the newly created migration file.

// create_coins_table.php

public function up()
{
    Schema::create('coins', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->integer('year');
        $table->integer('price');
        $table->timestamps();
    });
}

Next, migrate the table.

Related Posts
1 of 39
php artisan migrate

Now, code the store function inside CoinController.php file.

use App\Coin; 

public function store(Request $request)
 {
        $coin = new Coin;
        $coin->name = $request->name;
        $coin->year = $request->year;
        $coin->price = $request->price;

        $coin->save();

        return response()->json(['success' => 'Coin has been successfully added'], 200);
 }

Also, define the post route for a coin to save in the database.

// web.php

Route::post('/coins', 'CoinController@store');

Step 4: Send Post request and save the coin.

First, we need to install the vue-axios module for this application. So let’s do that.

npm install vue-axios --save-dev

Now, use this module.

// app.js

import VueAxios from 'vue-axios';
import axios from 'axios';

require('./bootstrap');

window.Vue = require('vue');
Vue.use(VueAxios, axios);

Vue.component('coin-add-component', require('./components/AddComponent.vue'));

const app = new Vue({
    el: '#app'
});

Okay, so now we just need to send a post request that contains the coin data.

// AddComponent.vue

export default {
      data() {
         return {
            coin: {}
         }
      },
      methods: {
         addCoin() {
            let uri = 'http://localhost:8000/coins';
            this.axios.post(uri, this.coin).then((response) => {
               window.location.reload();
            });
         }
      }
   }

If you try to send the post request, then you can get the 200 response code with success data.

Step 5: Make chart component to display the charts.

We are going to display Bitcoin’s chart throughout the years. I have hardcoded the query right now, but in real-time, it is dynamic. So, first, we are going to fetch the Bitcoin’s data from the database. For that, we need to define the route and write the query in the controller file.

Route::get('/coins', 'CoinController@index');

Write the index function in the CoinController.php file.

// CoinController.php

public function index()
{
   $coins = \DB::table('coins')
                ->where('name','=','Bitcoin')
                ->orderBy('year', 'ASC')
                ->get();
    return response()->json($coins);
}

Now, create a ChartComponent.vue file inside components folder.

<script>
import { Line } from 'vue-chartjs';

export default {
   extends: Line,
   mounted() {
         let uri = 'http://localhost:8000/coins';
         let Years = new Array();
         let Labels = new Array();
         let Prices = new Array();
         this.axios.get(uri).then((response) => {
            let data = response.data;
            if(data) {
               data.forEach(element => {
               Years.push(element.year);
               Labels.push(element.name);
               Prices.push(element.price);
               });
               this.renderChart({
               labels: Years,
               datasets: [{
                  label: 'Bitcoin',
                  backgroundColor: '#FC2525',
                  data: Prices
            }]
         }, {responsive: true, maintainAspectRatio: false})
       }
       else {
          console.log('No data');
       }
      });            
   }
}
</script>

Here, I have sent the get request to the Laravel server and get the bitcoin data. I have stored that data into an array and then pass that data to the chart configuration object.

Note: I have used Line Chart. You can use Bar Chart, Doughnut Chart, Pie Chart

You can find more configuration at this documentation.

Step 6: Register ChartComponent.vue in app.js file.

Our final app.js file looks like this.

// app.js

import VueAxios from 'vue-axios';
import axios from 'axios';

require('./bootstrap');

window.Vue = require('vue');
Vue.use(VueAxios, axios);

Vue.component('coin-add-component', require('./components/AddComponent.vue'));
Vue.component('chart-component', require('./components/ChartComponent.vue'));

const app = new Vue({
    el: '#app'
});

Also, use this chart component inside welcome.blade.php file.

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <title>Add Coin Details</title>
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <link href="{{ asset('css/app.css') }}" rel="stylesheet" />
</head>
<body>
   <div class="container" id="app">
       <coin-add-component></coin-add-component>
       <chart-component></chart-component>
   </div>
   <script>
        window.Laravel = <?php echo json_encode([
            '_token' => csrf_token(),
        ]); ?>
    </script>
   <script src="{{ asset('js/app.js') }}" type="text/javascript"></script>
</body>
</html>

 

 

Finally, Creating charts with Laravel Vue js Chart js Tutorial With Example is over. Thanks for taking.

Fork Me On Github

 

7 Comments
  1. Shirshak says

    why you stopped writing tutorial bro?

    Thanks

    hoping more

    1. Krunal says

      Thanks for appreciating. I am trying my best to come up with latest web development tutorials.

  2. samira says

    the data is not displaying on the graph, can u help me please

  3. Ryan AR Liem says

    Good tutorial, bro. This really help me to try implement chart.js using vue.js in laravel 5. If you mind, can I use your tutorial as one of my source material for writing some blog?

    1. Krunal says

      Thanks for the appreciation. Actually, my suggestion is not to write my post. You can create your own.

      1. Ryan AR Liem says

        Sure, that should be good. It would be easy to write something that you understand in your own way. Or should I call it as “self practice”? Thank you again for your advice.

        1. Krunal says

          Thanks!!

Leave A Reply

Your email address will not be published.

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