2

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 Answer 1

2
+300

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.

Sign up to request clarification or add additional context in comments.

2 Comments

OK, that makes sense. However, my issue is passing through the formatter because I need the datalabel to be in USD like $12,000. Any thoughts on that?
You can use the formatter function to format the text, you just have to be careful with escaping since you're writing a string to PHP that will have to escape special characters in both PHP and JS. Please see my updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.