I’ve recently been trying out Laravel Livewire (a new JS framework for adding front-end interactivity to your Laravel applications) by updating a personal project of mine, a home network monitoring tool. This post explains how I built auto-updating (“real time”) charts using Laravel Livewire and ChartJS.

Introduction

Before trying Livewire, I was using VueJS & Axios for interactive UI components such as auto-updating dashboard panels (e.g. WAN / broadband status & speeds, notifications etc) and tables of data with tools for sorting and filtering. Replacing these using Livewire has been super easy so far!

On my main dashboard there are also numerous ChartJS charts which automatically refresh every X seconds to show new any data that has arrived (e.g. WAN / broadband speed tests, number of DNS queries etc). As it’s only a small side project, I’d already decided that I was happy with polling the server for updates, rather than complicating my setup by using Web Sockets.

Luckily Laravel Livewire has a polling feature built in - simply adding wire:poll.10s to the root element in the component will make Livewire update the component every 10 seconds. This works great in most circumstances, however it wasn’t working with my charts as the JS had already run to initialise the chart and it wasn’t recreating them.

There is nothing in the Livewire docs that covers working with charts. After doing a bit of research, I came across issue #774 in GitHub, which discussed a way of updating ChartJS instances by using Livewire events. I used this as the base idea for my implementation, but adding a few improvements.

How it works

  • On the first render of the Livewire component, the initial chart data is retrieved from the database and combined with the configuration needed to render the chart, and is pushed into the blade view file as JavaScript to run on the initial page load. When viewed in a browser, the page loads, the JavaScript runs and the chart appears. The Livewire component remembers that the chart has been initially rendered by storing it’s ID and a MD5 hash of the data.
  • On subsequent renders of the component (triggered by the Livewire polling), the database is queried again to retrieve the data and another MD5 hash generated from it. The new hash is compared to the old, and only if it is different (meaning the data has changed), an event is emitted from the server side containing the updated dataset(s). The JavaScript then receives this event and uses the ChartJS API to update the rendered chart in the browser. The updated MD5 hash is remembered by the component for the next render.

#laravel #web development #chartjs #laravel livewire

Real time charts with Laravel Livewire & ChartJS
23.70 GEEK