Current Version:6.1
Laravel Version:5.X
PHP Version:7.X
Charts The laravel charting package. Github Page

# Installation

# Require the package

To install the package you'll need to use composer. So simply copy and paste the following code in your terminal, while you're in the laravel application directory.

composer require consoletvs/charts:6.*

# Service Provider

If you're using Laravel 5.5 or higher you may skip this step.

We need a way to tell Laravel that charts is there, the way to go is to register the service provider in the application configuration. To do such, you'll need to go to the config/app.php file and add the following line in the providers array:

ConsoleTVs\Charts\ChartsServiceProvider::class,

# Publish the configuration

This is one of this optional steps, but it's recommended if you wish to tweak the charts configuration. Simply type the following command in the terminal while you're in the application directory.

php artisan vendor:publish --tag=charts_config

# Usage

# Create a chart

The first step is to create a chart. If you come from older versions of the library you would think of this as creating the typical Charts::create(...) in the controller where you wish to create the chart. Instead, Charts > 6.0 comes with a fresh and cool way to create charts, templates or whatever you want without repeating code. The main feature we have is the fact that you may now create charts or chart templates with a simple command, more less how you create any Laravel middleware, notification, mailable, etc. In fact, you just need to type the following:

php artisan make:chart <Name> <Library?>
Check out the available charts by looking at the folders here: //goo.gl/k6Yn5c or you may check the latest section in this page.

The code above will create a simple chart template in the App\Charts namespace. It's usefull to think "why" you want to use this chart class for. You may think of it as one of the following ways:

  • Individual charts
  • Chart templates

The following code is an example of a generated chart using Chartjs as the library (the default one):

<?php

namespace App\Charts;

use ConsoleTVs\Charts\Classes\Chartjs\Chart;

class ExpoChart extends Chart
{
 /**
 * Initializes the chart.
 *
 * @return void
 */
 public function __construct()
 {
  parent::__construct();
 }
}

# Individual charts

Great if the same charts with the same datasets and/or data are placed in diferent areas.

Individual charts are the way of thinking about the classes as standard 1 class 1 chart where you add the datasets and the chart configuration in the class __construct(). This pretty much allows you to call it from the outside (controller) in a fancy way.

# Chart templates

Great if your application have a lot of charts and you want the same chart settings on them.

Chart templates are great if your application share a lot of common style in the same library. For example if you have a lot of charts in chartjs and all of them share the same settings (axes, legend configuration, axes, ...) you may prefer to use it as a template. The way it should work is simple, you just define the common settings among the charts in the chart class __construct() and when called from outside (a controller for example) you'll then need to add the datasets to the charts.

# Controller usage

Again, depending on the approach you chosed you'll need to do diferent things with the chart iself, but in all cases, you'll need to initiate a chart instance. In the following example we're using SampleChart as the chart name we generated using the following command:

php artisan make:chart SampleChart Chartjs <?php

namespace App\Http\Controllers;

use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChartsController extends Controller
{
 /**
 * Show a sample chart.
 *
 * @return Response
 */
 public function chart()
 {
  $chart = new SampleChart;
  // Additional logic depending on the chart approach
  return view('chart_view', ['chart' => $chart]);
 }
}

# View usage

We'll follow the example we provided in the controller usage to explain how the chart should be rendered in the view. First of all, and most important, we need to keep in mind that charts do not provide any assets for the charting libraries.

Charts do not provide any assets (CSS / JS) for any of the charting libraries.

You'll find information below about the supported libraries, what version does charts support and how to import them. Right now, we will follow the example and first of all import chartjs in our HTML. Once it's imported, you'll need to call two diferent methods on the chart variable to render the chart.

  • container()
  • script()

# container()

Renders the HTML of the chart. This includes the container, the CSS or HTML options for sizes etc. It contains no JS logic.

# script()

Renders the JS logic of the chart. It's important to keep it in a diferent area if you're using any JS frontend framework like VueJS. This method will create a <script>...</script> section and will add all the JS logic of the chart.

Charts support turbolinks in all of the charts. In fact, this website uses turbolinks.

# Example view

<!DOCTYPE html>
<html>
 <body>

  <div>{!! $chart->container() !!}</div>

 <script src="path/to/Chart.js/2.7.1/Chart.min.js" charset="utf-8"></script>
 {!! $chart->script() !!}
 </body>
</html>
This example will give you an exception, because it needs at least 1 dataset to display the chart. Do not panic and continue the reading to see how the example evolves.

# Chart datasets

# Add a dataset to a chart.

To add a dataset to the chart, you simply need to call the dataset() method and pass in the nessesary data to create it. Once called, it will return the dataset class, allowing you to modify the options or call additional option presets depending on the charting library.

# dataset()

To show an example of this, we will modify the controller we previously created. The convention of what the dataset method accept, is the following:
dataset(string $name, string $type, $data)
The name is the string that will show mostly in the legends of the chart. the type is a more complicated subject, as it changes depending on the library. For example, for Chartjs, there is something called 'pie'. The 'pie' type is how you define a pie chart in the charting library, BUT other libraries like Fusioncharts does not have a 'pie' type, instead, they do have a 'pie2d' type. So keep in mind that the chart type depends on the library you're working with. The data in the other hand can be an array or a collection containing the values of the chart.

The dataset type depends on the library itself, there is no predefined types, it will simply be placed where the charting library expects it to be, so take into consideration that each charting library may use diferent types for the same end-result.
<?php

namespace App\Http\Controllers;

use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChartsController extends Controller
{
 /**
 * Show a sample chart.
 *
 * @return Response
 */
 public function chart()
 {
  $chart = new SampleChart;
  // Add the dataset (we will go with the chart template approach)
  $chart->dataset('Sample', 'line', [100, 65, 84, 45, 90]);
  return view('chart_view', ['chart' => $chart]);
 }
}
Please note that the chart will only display X values, corresponding to this: X = count($chart->datasets), so in other words, it will only display as values as labels defined. You may know more about labels as you follow along the tutorial.

# Options & Configuration

# Customization Freedom

One of the major issues charts < 6.0 faced is the fact that people wanted custom charts, custom features, and this went to a point where the library iself was unmaintainable. This is not the case in this new version. We now require diferent configuration for each library and to compensate for this, we allow each and every option of the configuration of the chosen supported charting library.

# Library dependency

Depending on each library you'll need to setup diferent configuration or chart options. This is a major change from the old charts package. The older version allowed you to replicate a chart with every supported charting library with the same configuration. Well, this is not the case now. because of the freedom we get in the customization settings, you'll now need to define what configuration you want for your chart.

# Setting chart options

Listen carefully, because this is what makes the point for everything. But fear not, it's not the only way you have to setup the configuration a we provide a preset of options on each charting library.

Charts have diferent presets for options already setup depending on the chosen charting library.

To set the chart options, you'll make use of a function called options(). This public function is present in the chart calss. So it's accesible from the chart __construct() or in the controller iself. This option is the only one you'll need to configure the chart at your needs. It's basically an array that is later converted into a JS object, and appended correctly in the chart library. It stores the global chart configuration.

Do not get confused between the chart options and the dataset options!

To show how this works, we'll change the example chart we created before, by configuration the chart a bit.

While you learn how to customize the chart without any presets, please understand you'll need to know what options does the library you're working with give you. In the example we're using Chartjs: //www.chartjs.org/docs/latest/

Image we want to set the chartjs legend to get hidden in our chart, by reading the documentation we find out that the options object contains diferent data, in there we can find the legend namespace that contains an object with few settings, one of it it's display. Setting this option to false, will not display the legend. The way we have to set this option in the chart is by setting the options array as if it was the JS object. so, in our chart, we will need to call the options() method and pass in the array with the settings we want to apply. Fear not, calling the method 2 times does not remove the older setting, instead, it merges them. To reproduce an example on how to do this, We will modify the chart class we created earlier. (We will also append some labels, check the shared options below to know more)

<?php

namespace App\Charts;

use ConsoleTVs\Charts\Classes\Chartjs\Chart;

class ExpoChart extends Chart
{
 /**
 * Initializes the chart.
 *
 * @return void
 */
 public function __construct()
 {
  parent::__construct();

  $this->labels(['One', 'Two', 'Three', 'Four', 'Five'])
   ->options([
    'legend' => [
     'display' => false
    ]
   ]);
 }
}

This chart class will, from now on, hide the legend as the configuration will be applied to the chart.

# Chart basic (shared) options

There are a few methods you can use in all charts (regardless of the charting library). Theese includes:

  • dataset(string $name, string $type, $data) - Adds a new dataset to the chart.
  • labels($labels) - Set the chart labels.
  • options($options, bool $overwrite = false) - Set the chart options.
  • container(string $container = null) - Set the chart container (if you need your own view). Display the view if no parameter is set.
  • script(string $script = null) - Set the chart script. (if you need your own view). Display the view if no parameter is set.
  • type(string $type) - Force a chart type, if not set, the first dataset type found will be used.
  • height(int $height) - Set the chart height. Null / 0 by default = auto
  • width(int $width) - Set the chart width. Null / 0 by default = auto
  • loader(bool $loader) - Determines if the chart loader should be displayed. Default to true
  • loaderColor(string $color) - Set the chart loader color. Default: #22292F
  • reset() - Reset the chart options.

# Setting Dataset Options

The dataset options works the same way as the chart options, but the options would need to be applied in the dataset object that the dataset() method returns. In fact, if we want, for example, to change the color of the line chart to a diferent one (we're still using the chartjs example) we would see in their documentation that the line chart have a 'borderColor' option. So we would modify the controller with the following data:

<?php

namespace App\Http\Controllers;

use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChartsController extends Controller
{
 /**
 * Show a sample chart.
 *
 * @return Response
 */
 public function chart()
 {
  $chart = new SampleChart;
  // Add the dataset (we will go with the chart template approach)
  $chart->dataset('Sample', 'line', [100, 65, 84, 45, 90])
   ->options([
    'borderColor' => '#ff0000'
   ]);
  return view('chart_view', ['chart' => $chart]);
 }
}

# Dataset basic (shared) options

There are a few methods you can use in all datasets (regardless of the type, or charting library). Theese includes:

  • type(string $type) - Set the dataset type.
  • values($values) - Set the dataset values.
  • options($options, bool $overwrite = false) - Set the dataset options.

# Presets alternative

Psss! This is the easy way

Yes, reading docs is not what your want to do, you prefer to just type some easy code and see things working as you wish, so why not create some presets? Charts comes with diferent presets you may use for either, charts options and datasets depending on each charting library. You may read the following section to know more.

# Presets

# Using a preset

Using a preset is pretty easy, and requires no understanding of the charting library itself. To use a preset you'll just need to call the preset method in the object. Presets work on either chart settings or dataset settings.

You may use presets on chart settings or dataset settings.

To know what presets are available on your charting library you'll need to check the official traits we provide. Theese traits are added on the chart and the dataset at the moment of creation, so they are available depending on the chart type. We structured the directories to make it clear what's available as presets, so to know more you'll need to check the official repository and see what's available.

Check the available presets here: //goo.gl/gsvURa

By pressing the link you can see that there are multiple charting libraries supported. Choose the one you are using and you'll see 2 files. Chart.php and Dataset.php As you may already guess, Chart.php stores the chart configuration presets and Dataset.php stores the dataset configuration presets.

Theese presets have been isolated from the chart class so you can see what they do and what arguments do they accept without understanding how charts works under the hood.

To show an example of a chart with a few presets, we'll modify the chart and the dataset from the example, as we previously added the "hide legends" feature, we will now use a preset that pretty much does the same (You may check it in the chartjs Chart.php presets.

<?php

namespace App\Charts;

use ConsoleTVs\Charts\Classes\Chartjs\Chart;

class ExpoChart extends Chart
{
 /**
 * Initializes the chart.
 *
 * @return void
 */
 public function __construct()
 {
  parent::__construct();

  $this->displayLegend(false);
 }
}

Let's now use the same tactic to change the color of the dataset we created using a preset. Again we may check that the Chartjs Dataset.php hace a color preset.

<?php

namespace App\Http\Controllers;

use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChartsController extends Controller
{
 /**
 * Show a sample chart.
 *
 * @return Response
 */
 public function chart()
 {
  $chart = new SampleChart;
  // Add the dataset (we will go with the chart template approach)
  $chart->dataset('Sample', 'line', [100, 65, 84, 45, 90])
   ->color('#ff0000');
  return view('chart_view', ['chart' => $chart]);
 }
}
A note for pretty much all color / background color presets: They accept an array / Collection to format a pie-style dataset.

# Loading charts over AJAX / API

# Why?

Loading charts over an API is a better smooth way to show the charts if the calculation of the chart values takes a long time to compute. The website will render and will show the chart in a loader state. Once the ajax request is successfull, it will load the chart with the recieved data.

# Controller

You'll need to create the chart. The settings and the labels need to be set in the controller:

<?php

namespace App\Http\Controllers;

use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChartsController extends Controller
{
 /**
 * Show a sample chart.
 *
 * @return Response
 */
 public function chart()
 {
  $chart = new SampleChart;
  $api = url('/test_data');
  $chart->labels(['test1', 'test2', 'test3'])
   ->load($api)
  return view('chart_view', ['chart' => $chart]);
 }
}

# API response

The API response for the chart to load will need to be the following:

<?php

namespace App\Http\Controllers;

use App\Charts\SampleChart;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ChartsController extends Controller
{
 /**
 * Computes the sample chart.
 *
 * @return Response
 */
 public function response()
 {
  $chart = new SampleChart;
  $chart->dataset('Sample Test', 'bar', [3,4,1])->color('#00ff00');
  $chart->dataset('Sample Test', 'line', [1,4,3])->color('#ff0000');
  return $chart->api();
 }
}

As you can see, we add the datasets outside the chart creation and then we just call it as an AJAX request in the chart's JS. You do not need to take any other actions. As a quick note; the chart loader and it's color can be enabled / disabled or set with the base chart methods (check the methods above).

# Advanced

# Pie-style datasets.

We tested a few things with basic pie / doughnut charts, but they normally require additional data formating. Due to this issue, we decided to set a public property in the chart depending on the charting library, that set what charts are actually special and require that kind of format. You may also notice, not all charting libraries need this. If you want an example, check the //goo.gl/Lxk2Pv "specialDatasets" attribute. Again, don't worry, we take care of it :). Remember, to use an array of colors instead of a color string if you're using a preset.

# The chart JS variable

All charts are binded to a JS variable, by default, this variable is generated in the constructor, creating a random 25 characters long id with only lowercase alphabetic characters. This is the ID of the chart. If you ever need to modify the chart after it's rendered (eg: because you want to add, remove data) you may acces it in the window.{{ $chart->id }} JS variable.

# Supported libraries

# Versioning

  • Chartjs: ~ 2.7.1
  • Highcharts: ~ 2.7.1
  • Fusioncharts: ~ 3.12.2
  • Echarts: ~ 4.0.2

# CDNs

<script src=//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js charset=utf-8></script>
<script src=//cdnjs.cloudflare.com/ajax/libs/highcharts/6.0.6/highcharts.js charset=utf-8></script>
<script src=//cdn.jsdelivr.net/npm/[email protected]/fusioncharts.js charset=utf-8></script>
<script src=//cdnjs.cloudflare.com/ajax/libs/echarts/4.0.2/echarts-en.min.js charset=utf-8></script>

© 2018 Èrik Campobadal. All rights reserved.