Search code examples
javascriptphpflotlaravel-5laravel-blade

Flot Chart plot points with dynamic PHP variables


I have a table that is displaying numbers via laravel php. The numbers are based on a one week time period and the values associated with each day update accordingly upon refresh. Now I need to get this data inside of a flot chart. A typical flot chart will have static points like this:

var data = [[0, 0], [1, 10], [2,5], [3, 12], [4, 9], [5, 4], [6, 2]];

But I need each point to be dynamic like this:

@foreach($days as $day)
 var data = [[{{ $day['carbon']->format('F j, Y') }},{{ $day['total'] }}]]
@endforeach 

And of course this breaks the chart and it doesn't work. I am kinda stuck here. Any suggestions would be greatly appreciated.


Solution

  • First build the full array in PHP. Don't worry about javascript yet.

    Something like this:

    $data = [];
    foreach($days AS $day) {
        $data[] = [$day['carbon']->format('F j, Y'), $day['total']];
    }
    

    Ideally, do this in your controller. Not in the view.

    Now, in your view it becomes easy:

    <script>
    var data = {!! json_encode($data) !!};
    

    Note the different {!! tag, that tells Laravel not to escape the output.