How can I pass a javascript callback to a PHP construct in Laravel-Charts

570 views Asked by At

I am using the laravel-charts package in Laravel 7. I added the datalabels plugin for chartjs into the Chart object like this:

$this->options = [
    'responsive' => true,
    'maintainAspectRatio' => false,
    'legend' => [ 'display' => false ],
    'plugins' => [
        'datalabels' => [
            'color' => 'white',
            'weight' => 'bold',
            'font' => ['size' => 14],
            'formatter' => ''     
    ]
]

In another version when I was using vue.js and vue-chartjs, I was able to format the lable using this:

plugins: {
    datalabels: {
        formatter: function(value, context) {
            return '$' + Number(value).toLocaleString();
         },
   }
}

As you can see, the javascript is passed as a PHP array. I cannot figure out how to pass that formatter to my laravel-charts version.

Any help is greatly appreciated.

1

There are 1 answers

2
Christos Lytras On BEST ANSWER

Laravel Charts plugins option has to be a string that's representing a plain Javascript object. I couldn't find any actual documentation, but you can read a related issue here "How to use ChartsJs plugin Datalabels js?".

You'll have to pass it like this:

$chart = new ChartTest;
$chart->labels(['One Thousand', 'Two Thousand', 'Three Thousand', 'Four Thousand']);
$chart->dataset('My dataset', 'bar', [1000, 2000, 3000, 4000]);

$chart->options([
    // The whole plugins element is a string representing a JS object with plugins options
    'plugins' => "{
        datalabels: {
            color: 'red',
            font: {
                size: 14,
                weight: 'bold'
            },
            formatter: (value) => `\\$\${value}`
        }
    }"
]);

return view('chart', ['chart' => $chart]);

Will apply chartjs-plugin-datalabels options:

Laravel ChartsJS

PS: The weight property has to be inside the font object like in my example.