This blog post was written under the Pusher Guest Writer program.

In this tutorial, we will build a realtime chart which will show the current active users, represented by a bar chart, without reloading the page. This is just a demo example to showcase the functionality of creating dynamic charts in realtime. You can extend this to create numerous reports in realtime for your application.

Today, we will create a realtime chart system using Laravel and Pusher. With the release of Echo, Laravel has provided an out of the box solution for implementing realtime data synchronisation using event broadcasting. It is simple and we can get started in a matter of minutes.

A basic understanding of Laravel and Vue is needed to follow this tutorial.

Setup an App on Pusher

We need to sign up on Pusher and create a new app.

Install Laravel, Pusher SDK and Echo

First, we will grab a fresh copy of Laravel:

laravel new realtime-chart-laravel-pusher

This will install the latest version of the Laravel framework and download the necessary dependencies. Next, we will install the Pusher PHP SDK using Composer:

composer require pusher/pusher-php-server

Next, we will install the JavaScript dependencies:

npm install

Now, we need to install the Javascript libraries necessary for realtime event broadcasting and displaying charts: Laravel Echo, chart.js and Pusher JS

npm install --save laravel-echo pusher-js chart.js

We will require some form of user authentication mechanism to demonstrate the functionality. Let us use the default authentication scaffolding provided by Laravel:

php artisan make:auth

Configuration

First, we need to set the APP_ID, APP_KEY, APP_SECRET and APP_CLUSTER in the environment file. We can get these details in our Pusher app dashboard:

# .env

BROADCAST_DRIVER=pusher

PUSHER_APP_ID=your-pusher-app-id
PUSHER_APP_KEY=your-pusher-app-key
PUSHER_APP_SECRET=your-pusher-app-secret
PUSHER_APP_CLUSTER=your-pusher-app-cluster

Next, we need to create a fresh Echo instance in our applications’s JavaScript. We can do so at the bottom of our resources/assets/js/bootstrap.js file:

import Echo from "laravel-echo"

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: 'your-pusher-app-key',
    cluster: 'ap2',
    encrypted: true
});

Our Application

The core feature of our app is the number of active users shown as a realtime bar chart. Whenever a user joins or leaves this page, the graph for online users will be automatically updated. The code is available on a Github repository for cloning and understanding purposes.

Creating a Chart

We will create a bar chart with hard coded default values. Later, we will retrieve these values in realtime and update the chart accordingly.

To create a chart, we need to first instantiate the Chart class. Let us first grab the element or context and then create a chart instance with the default datasets:

# HTML

<canvas id="myChart" height="100"></canvas>
# ES6

let ctx = document.getElementById("myChart");

let myChart = new Chart(ctx, {
    type: 'bar',
    data: {
        labels: ['Online'],
        datasets: [{
            label: '# of Users',
            data: [3],
            borderWidth: 1
        }]
    }
});

Below is the screenshot for how the graph would look like:

Mapping Realtime Values for Online Users

As you can see in the above code sample, we are populating the values through data property in the datasets array. For the sake of demonstration we have hard coded the values. Let us now map it to the realtime values.

First we will create a property in our component to reflect the count of registered and online users. Initially, we will set it to the default values:

data() {
    return {
        count: 0
    }
},

Let us now create a method to draw our chart using the values specified above.

drawChart() {
    let ctx = document.getElementById("myChart");
    let myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Online'],
            datasets: [{
                label: '# of Users',
                data: [this.count],
                borderWidth: 1
            }]
        },
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero:true
                    }
                }]
            }
        }
    });
}

Next, we need to update the above count in realtime whenever a new user joins the page or some user leaves the page.

We’ll implement that with Echo and it is super simple. Let us go and fill out our update method in the Example Vue component.

update() {
    Echo.join('chart')
        .here((users) => {
            this.count = users.length;
            this.drawChart();
        })
        .joining((user) => {
            this.count++;
            this.drawChart();
        })
        .leaving((user) => {
            this.count--;
            this.drawChart();
        });
}

join is used when we want to join a presence channel and that is used to tell us who else is on the page. Presence channels are automatically private channels. We do need to authenticate them.

here gives us a list of users that are also present on the same page.

joining will be executed whenever a new user joins the channel or page in the above scenario.

leaving will be executed whenever a user leaves the channel.

Authorization

Every presence channel is a private channel. Laravel Echo will automatically call the specified authentication route. However, we still need to write the authentication logic which will actually authorize the user to listen to a particular channel.

Authorization logic is written in the routes/channels.php. The authorization logic for our chart channel is:

Broadcast::channel('chart', function ($user) {
    return [
        'name' => $user->name
    ];
});

We are not going to return true or false. If the user is authenticated to listen on this presence channel we are going to return an array of data that we want returned to that callback in the update method.

You can write the authentication logic as required for your application in the above callback and return null if authorization fails.

Vue Component

That’s it! Now, whenever a user joins or leaves the page, it will be updated in the chart in realtime.

Below is our Example component written using Vue.js

<template>
    <div class="container">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Example Component</div>

                    <div class="panel-body">
                        <canvas id="myChart" height="100"></canvas>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    import Chart from 'chart.js'

    export default {
        data() {
            return {
                count: 0,
                labels: ['Online']
            }
        },
        mounted() {
            this.update();
            this.drawChart();
        },
        methods: {
            drawChart() {
                let ctx = document.getElementById("myChart");
                let myChart = new Chart(ctx, {
                    type: 'bar',
                    data: {
                        labels: this.labels,
                        datasets: [{
                            label: '# of Users',
                            data: [this.count],
                            borderWidth: 1
                        }]
                    },
                    options: {
                        scales: {
                            yAxes: [{
                                ticks: {
                                    beginAtZero:true
                                }
                            }]
                        }
                    }
                });
            },
            update() {
                Echo.join('chart')
                    .here((users) => {
                        this.count = users.length;
                        this.drawChart();
                    })
                    .joining((user) => {
                        this.count++;
                        this.drawChart();
                    })
                    .leaving((user) => {
                        this.count--;
                        this.drawChart();
                    });
            }
        }
    }
</script>

Below is the quick demonstration of our application:

Conclusion

In this article, we have covered how to create a realtime chart using Laravel and Pusher. We have covered the configuration options necessary to get started, and the example above should help you fill in the gaps and give an overview of some of the other configuration options available to you.

The code is hosted on public Github repository. You can download it for educational purposes. How do you intend to use Laravel and Pusher? Can you think of any advanced use cases? What are they? Let us know in the comments!