Simple package to facilitate and automate the use of charts in Laravel 5.x using Chartjs v2 library

Overview

laravel-chartjs - Chart.js v2 wrapper for Laravel 5.x

Simple package to facilitate and automate the use of charts in Laravel 5.x using the Chart.js v2 library from Nick Downie.

Setup:

composer require fx3costa/laravelchartjs

And add the Service Provider in your file config/app.php:

Fx3costa\LaravelChartJs\Providers\ChartjsServiceProvider::class

Finally, for now, you must install and add to your layouts / templates the Chartjs library that can be easily found for download at: http://www.chartjs.org. This setting will also be improved.

Usage:

You can request to Service Container the service responsible for building the charts and passing through fluent interface the chart settings.

$service = app()->chartjs
    ->name()
    ->type()
    ->size()
    ->labels()
    ->datasets()
    ->options();

For now the builder needs the name of the chart, the type of chart that can be anything that is supported by chartjs and the other custom configurations like labels, datasets, size and options.

In the dataset interface you can pass any configuration and option to your chart. All options available in chartjs documentation are supported. Just write the configuration with php array notations and its work!

Advanced chartjs options

Since the current version allows it to add simple json string based options, it is not possible to generate options like:

    options: {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        quarter: 'MMM YYYY'
                    }
                }
            }]
        }
    }

Using the method optionsRaw(string) its possible to add a the options in raw format:

Passing string format like a json

        $chart->optionsRaw("{
            legend: {
                display:false
            },
            scales: {
                xAxes: [{
                    gridLines: {
                        display:false
                    }  
                }]
            }
        }");

Or, if you prefer, you can pass a php array format

$chart->optionsRaw([
    'legend' => [
        'display' => true,
        'labels' => [
            'fontColor' => '#000'
        ]
    ],
    'scales' => [
        'xAxes' => [
            [
                'stacked' => true,
                'gridLines' => [
                    'display' => true
                ]
            ]
        ]
    ]
]);

Examples

1 - Line Chart / Radar Chart:

// ExampleController.php

$chartjs = app()->chartjs
        ->name('lineChartTest')
        ->type('line')
        ->size(['width' => 400, 'height' => 200])
        ->labels(['January', 'February', 'March', 'April', 'May', 'June', 'July'])
        ->datasets([
            [
                "label" => "My First dataset",
                'backgroundColor' => "rgba(38, 185, 154, 0.31)",
                'borderColor' => "rgba(38, 185, 154, 0.7)",
                "pointBorderColor" => "rgba(38, 185, 154, 0.7)",
                "pointBackgroundColor" => "rgba(38, 185, 154, 0.7)",
                "pointHoverBackgroundColor" => "#fff",
                "pointHoverBorderColor" => "rgba(220,220,220,1)",
                'data' => [65, 59, 80, 81, 56, 55, 40],
            ],
            [
                "label" => "My Second dataset",
                'backgroundColor' => "rgba(38, 185, 154, 0.31)",
                'borderColor' => "rgba(38, 185, 154, 0.7)",
                "pointBorderColor" => "rgba(38, 185, 154, 0.7)",
                "pointBackgroundColor" => "rgba(38, 185, 154, 0.7)",
                "pointHoverBackgroundColor" => "#fff",
                "pointHoverBorderColor" => "rgba(220,220,220,1)",
                'data' => [12, 33, 44, 44, 55, 23, 40],
            ]
        ])
        ->options([]);

return view('example', compact('chartjs'));


 // example.blade.php

<div style="width:75%;">
    {!! $chartjs->render() !!}
</div>

2 - Bar Chart:

// ExampleController.php

$chartjs = app()->chartjs
         ->name('barChartTest')
         ->type('bar')
         ->size(['width' => 400, 'height' => 200])
         ->labels(['Label x', 'Label y'])
         ->datasets([
             [
                 "label" => "My First dataset",
                 'backgroundColor' => ['rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)'],
                 'data' => [69, 59]
             ],
             [
                 "label" => "My First dataset",
                 'backgroundColor' => ['rgba(255, 99, 132, 0.3)', 'rgba(54, 162, 235, 0.3)'],
                 'data' => [65, 12]
             ]
         ])
         ->options([]);

return view('example', compact('chartjs'));


 // example.blade.php

<div style="width:75%;">
    {!! $chartjs->render() !!}
</div>

3 - Pie Chart / Doughnut Chart:

// ExampleController.php

$chartjs = app()->chartjs
        ->name('pieChartTest')
        ->type('pie')
        ->size(['width' => 400, 'height' => 200])
        ->labels(['Label x', 'Label y'])
        ->datasets([
            [
                'backgroundColor' => ['#FF6384', '#36A2EB'],
                'hoverBackgroundColor' => ['#FF6384', '#36A2EB'],
                'data' => [69, 59]
            ]
        ])
        ->options([]);

return view('example', compact('chartjs'));


 // example.blade.php

<div style="width:75%;">
    {!! $chartjs->render() !!}
</div>

OBS:

This README, as well as the package, is in development, but will be constantly updated and I will keep you informed as soon as it is ready for production. Thank you for understanding.

Any questions or suggestions preferably open a issue!

License

LaravelChartJs is open-sourced software licensed under the MIT license.

Comments
  • stacked bar chart

    stacked bar chart

    really appreciate for nice plugin.

    let me know, how to create a stacked bar chart, I was tried to configure options with optionraw but doesn't work.

    thanks

    question 
    opened by ommyan 6
  • parse error, expecting `';'' or `'{'' when writing laravel-chartjs

    parse error, expecting `';'' or `'{'' when writing laravel-chartjs

    I don't know what is the main issue. I have already install laravel-chartjs extension to my laravel . And I attempted to copy the sample code in README to run in my laravel application. This is my code:

    screenshot

    When I ran that code, it didn't work. It shows the below error. screenshot 2

    I would like to know the exact issue and any possible solutions. Thanks.

    opened by Rana-xD 6
  • Class chartjs does not exist

    Class chartjs does not exist

    I am trying to create a laravel analytics applications, but after doing all that i was told in the documentation refer to: https://github.com/fxcosta/laravel-chartjs/blob/master/README.md

    I am getting the the following error: ReflectionException in Container.php line 749: Class chartsjs does not exist

    How do i solve this? Please help!

    opened by mtshikomba 5
  • Documentation is currently misleading

    Documentation is currently misleading

    "Call to undefined method Fx3costa\LaravelChartJs\Builder::size()"

    There's no size method in the latest tagged release, only in the master branch.

    opened by rzb 5
  • Method Illuminate\View\View::__toString() must not throw an exception

    Method Illuminate\View\View::__toString() must not throw an exception

    Hi, when i'm trying out the following Code i get that error

        <div class="container-fluid">
            <canvas id="BarChart" style="width:50%;"></canvas>
        </div>
    
        <?php
        $data = array(
                'Jan' => array(33),
                'Feb' => array(32),
                'Mar' => array(12)
        );
        ?>
    
        {!! app()->chartbar->render("BarChart", $data) !!}
    

    Error

    FatalErrorException in 8be385e208e531fc8df24170541811c5 line 0: Method Illuminate\View\View::__toString() must not throw an exception

    The strange thing is that a few days ago everything worked

    What could cause this error?

    edit: I downgraded to version 1.3.2 and everything worked fine

    opened by starkbaum 5
  • how can i add units to my chart help me =D

    how can i add units to my chart help me =D

    i tried this $options['scales']['yAxes']['scaleLabel']['display']=true; $options['scales']['yAxes']['scaleLabel']['labelString']="Data"; $chartjs = app()->chartjs ->name('pieChartUser') ->type('pie') ->size(['width' => 400, 'height' => 200]) ->options($options);

    opened by khelilo7 4
  • Render Chart on Tabs (Bootstrap)

    Render Chart on Tabs (Bootstrap)

    When I try to render multiple charts on tabs in bootstrap using your package it only displays one chart (on the starting active tab) but does not display on other tabs. Thanks. ul class="nav nav-tabs"> li class="active">a data-toggle="tab" href="#home">Home

  • li>a data-toggle="tab" href="#menu1">Menu 1 li>a data-toggle="tab" href="#menu2">Menu 2 /ul> div class="tab-content"> div id="home" class="body tab-pane fade in active" style="width: 95%;"> {!! $chartjs->render() !!} {{--
    --}} /div> div id="menu1" class="body tab-pane fade" style="width: 95%;"> {!! $chartjs->render() !!} {{--
    --}} /div> /div>

    bug 
opened by jocarullo 4
  • How tor write options with multi-level properly

    How tor write options with multi-level properly

    I am trying to figure out how to write optionas parameters and values properly. For example how can I write this option for chartjs using the options provided by laravel-chartjs?

    options: { scales: { yAxes: [{ ticks: { beginAtZero:true } }] } }

    opened by zihadt 4
  • Drawing PieChart issue

    Drawing PieChart issue

    Line chart works well. But bar chart and piechart doesn't work. I inputted code as your example code. But nothing appeared. I got this error...

    Chart.min.js:11 Uncaught TypeError: Cannot read property 'length' of null at n (Chart.min.js:11) at new t.Controller (Chart.min.js:11) at new t (Chart.min.js:12) at dashboard:84 at dashboard:91 n @ Chart.min.js:11 t.Controller @ Chart.min.js:11 t @ Chart.min.js:12 (anonymous) @ dashboard:84 (anonymous) @ dashboard:91

    Please help me

    opened by FredLopes0203 4
  • chart-pie-doughnut: js-legend-pie element is null

    chart-pie-doughnut: js-legend-pie element is null

    In chart-pie-doughnut.blade.php (but also in others) there's a stement which generates a legend for a pie chart:

    document.getElementById('js-legend-pie').innerHTML = PizzaChart.generateLegend();
    

    There are a couple of problems with this code:

    • It doesn't support multiple pie charts on 1 page because of the ID selector
    • There's no way to determine the output of the legend (it's a chart JS option which is currently not accessable within this package)

    To prevent javascript errors, it would be a solution to check if the element exists:

    var legend = document.getElementById('js-legend-pie');
    if (legend) {
        document.getElementById('js-legend-pie').innerHTML = PizzaChart.generateLegend();
    }
    

    It's no problem to fix this and create a pull request, but I wanted to discuss this with you first.

    opened by vdhicts 4
  • Number of datasets are limited in a Chart due to colours[] array.

    Number of datasets are limited in a Chart due to colours[] array.

    In current impl, number of datasets in any chart is limited to just 3. This seems is due to the colours[] array defined in config/chart.js.

    I have workedaround this issue by generating the colors for each dataset at run time. Thought this could be useful to other users of laravel-chartjs. Feel free to use the code below. Note: I have not done extensive testing but it seems to work for me.

    /resources/ChartBar.php (within method 'render')

            for($i = 0; $i < $datasetQnt; $i++) {
                // Pick a colour for a dataset at run time.
                $spread = 25;
                $r = rand(0+$spread,255-$spread);
                $g = rand(0+$spread,255-$spread);
                $b = rand(0+$spread,255-$spread);
                $color = "rgba($r, $g, $b, .7)";
    
                $dataset[$i] = array_column($data, $i);
                $dataset[$i] = implode(", ", $dataset[$i]);
                $colours[$i] = $color; //$this->colours[$i];
            }
    
    
    opened by AshishGupta001 4
  • Redirection when I click on the bar

    Redirection when I click on the bar

    Hello, I would like to be able to redirect to another page when the user clicks on the bar. I tried to search if someone tried to do it as I did not succeed but I did not find anything issuePNG Blade bladePNG Controller Controller

    opened by OPJKP 0
  • Documentation on how to use this library

    Documentation on how to use this library

    I stumbled on this library while looking for something to render charts with Laravel and ChartJS but I've found no documentation on how to use it, please, can anyone educate me on where to find the usage documentation? I don't understand that on the git page.

    opened by ken4ward 0
  • Render markup separately from scripts

    Render markup separately from scripts

    This is a bit more of a feature request, but it would be ideal if you could render the markup separately from the scripts.

    So then you can push your scripts out of the main body of the template to avoid conflict with other vue elements.

    Before:

    @section('body')
    <div class="chart">
        {{$chart->render()}}
    </div>
    @endsection
    

    After:

    @section('body')
    <div class="chart">
        {{$chart->markup()}}
    </div>
    @endsection
    @push('scripts')
        {{$chart->script()}}
    @endpush
    
    opened by jpswade 0
  • How to add option for animate in controller

    How to add option for animate in controller

    $chartMonth = app()->chartjs ->name('lineChart') ->type('line') ->size(['width' => 400, 'height' => 220]) ->labels(['January', 'February', 'March', 'April', 'May', 'June', 'July','August', 'September', 'October', 'November', 'December']) ->datasets([ [ "label" => "Total Lhp per Month", 'backgroundColor' => "rgba(38, 185, 154, 0.31)", 'borderColor' => "rgba(38, 185, 154, 0.7)", "pointBorderColor" => "rgba(38, 185, 154, 0.7)", "pointBackgroundColor" => "rgba(38, 185, 154, 0.7)", "pointHoverBackgroundColor" => "#fff", "pointHoverBorderColor" => "rgba(220,220,220,1)", 'data' => $months->toArray(), ] ]) ->options([ //what should i do here 'animation' ??

        ]);
    
    opened by Senrism 0
  • Releases(2.9.0)
    Owner
    Felix Costa
    CTO at Sotero Tech
    Felix Costa
    Makes waterfall charts easy with chartjs-2

    Installation npm install --save chartjs-plugin-waterfall Here's what it looks like: Usage Just import the plugin and add it to any chart that you want

    Ziegert Group 10 Jul 16, 2022
    An open-source visualization library specialized for authoring charts that facilitate data storytelling with a high-level action-driven grammar.

    Narrative Chart Introduction Narrative Chart is an open-source visualization library specialized for authoring charts that facilitate data storytellin

    Narrative Chart 45 Nov 2, 2022
    Crosshair plugin for ChartJS

    Chart.js plugin to draw vertical crosshair, zoom, interpolate values and sync chart interactions. Requires Chart.js 3.4.0 or later. Documentation Inst

    Abel Heinsbroek 118 Dec 12, 2022
    Smoothie Charts: smooooooth JavaScript charts for realtime streaming data

    Smoothie Charts is a really small charting library designed for live streaming data. I built it to reduce the headaches I was getting from watching ch

    Joe Walnes 2.2k Dec 13, 2022
    A Simple Dashboard Chart in Laravel Nova using Chart JS

    A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

    Kuncoro Wicaksono 177 Jan 4, 2023
    Ember Charts 3.5 2.3 L2 JavaScript A powerful and easy to use charting library for Ember.js

    Ember Charts A charting library built with the Ember.js and d3.js frameworks. It includes time series, bar, pie, and scatter charts which are easy to

    Addepar 793 Dec 7, 2022
    Free Bootstrap 5 Admin and Dashboard Template that comes with all essential dashboard components, elements, charts, graph and application pages. Download now for free and use with personal or commercial projects.

    PlainAdmin - Free Bootstrap 5 Dashboard Template PlainAdmin is a free and open-source Bootstrap 5 admin and dashboard template that comes with - all e

    PlainAdmin 238 Dec 31, 2022
    Simple HTML5 Charts using the tag

    Simple yet flexible JavaScript charting for designers & developers Documentation Currently, there are two versions of the library (2.9.4 and 3.x.x). V

    Chart.js 59.4k Jan 7, 2023
    J2CL and GWT Charts library based on CHART.JS

    Charba - J2CL and GWT Charts library based on CHART.JS What's Charba GWT Web toolkit doesn't have charting library available out of the box. There are

    Pepstock.org 56 Dec 17, 2022
    Simple responsive charts

    Big welcome by the Chartist Guy Checkout the documentation site at http://gionkunz.github.io/chartist-js/ Checkout this lightning talk that gives you

    Gion Kunz 26 Dec 30, 2022
    Simple, responsive, modern SVG Charts with zero dependencies

    Frappe Charts GitHub-inspired modern, intuitive and responsive charts with zero dependencies Explore Demos » Edit at CodePen » Contents Installation U

    Frappe 14.6k Jan 4, 2023
    A simple ember component for adding Charts

    Ember Chart This Ember CLI addon is a simple wrapper for ChartJS (v2.9). Compatibility Ember.js v3.12 or above Ember CLI v2.13 or above Node.js v10 or

    Ahmed Omran 136 Oct 24, 2022
    A simple script for pure javascript charts.

    MK Charts A simple pure Javascript for displaying circle charts. Demo: https://mkirschen.de/mk-scripts/mk-charts/ Circle charts To insert a chart all

    Marcus Kirschen 6 Dec 14, 2022
    JavaScript diagramming library for interactive flowcharts, org charts, design tools, planning tools, visual languages.

    GoJS, a JavaScript Library for HTML Diagrams GoJS is a JavaScript and TypeScript library for creating and manipulating diagrams, charts, and graphs. S

    Northwoods Software Corporation 6.6k Dec 30, 2022
    A plugin for the jQuery javascript library to generate small sparkline charts directly in the browser

    jQuery Sparklines This jQuery plugin makes it easy to generate a number of different types of sparklines directly in the browser, using online a line

    Gareth Watts 1.2k Jan 4, 2023
    Reusable JavaScript library for creating sketchy/hand-drawn styled charts in the browser.

    roughViz.js is a reusable JavaScript library for creating sketchy/hand-drawn styled charts in the browser, based on D3v5, roughjs, and handy. Why? Use

    Jared Wilber 6.4k Jan 4, 2023
    Synchro Charts is a front-end component library that provides a collection of components to visualize time-series data.

    Synchro Charts Synchro Charts is a front-end component library that provides a collection of components to visualize time-series data. You can learn m

    Amazon Web Services - Labs 60 Dec 29, 2022
    Progressive pie, donut, bar and line charts

    Peity Peity (sounds like deity) is a jQuery plugin that converts an element's content into a mini <svg> pie, donut, line or bar chart. Basic Usage HTM

    Ben Pickles 4.2k Jan 1, 2023
    Compose complex, data-driven visualizations from reusable charts and components with d3

    d3.compose Compose rich, data-bound charts from charts (like Lines and Bars) and components (like Axis, Title, and Legend) with d3 and d3.chart. Advan

    Cornerstone Systems 702 Jan 3, 2023