Google Timeline Charts using Laravel (PHP)

-1

I have a controller that queries the data, transforms it into JSON and sends it to the view (which contains the timeline).

The chart you're using is this: link

    public function monitor_sala()
{
    $data = [];

    $reservas = ReservaSala::all();


    foreach ($reservas as $reserva) {

        $obj = array(
          $reserva->nome, $reserva->sala, $reserva->hora_pegar, 
     $reserva->hora_devolver
    );
        array_push($data, $obj);
    }

    return view('salas.monitor', compact('data'));
}

This is the method that sends json (date) to the view ....

In the View the code looks like this:

     <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script><scripttype="text/javascript">
    google.charts.load("current", {packages:["timeline"]});
    google.charts.setOnLoadCallback(drawChart);
    function drawChart() {
        var container = document.getElementById('example5.1');
        var chart = new google.visualization.Timeline(container);
        var dataTable = new google.visualization.DataTable();
        dataTable.addColumn({ type: 'string', id: 'Room' });
        dataTable.addColumn({ type: 'string', id: 'Name' });
        dataTable.addColumn({ type: 'date', id: 'Start' });
        dataTable.addColumn({ type: 'date', id: 'End' });
        dataTable.addRows([
            <?php echo json_encode($data) ?>
            ]);
        var options = {
            timeline: { colorByRowLabel: true }
        };

        chart.draw(dataTable, options);
    }

</script>

<div id="example5.1" style="height: 100%"></div>

But it does not work, it only picks up when I put the sample data from the documentation. For what it says in the documentation you can use simple numbers to represent the time (so I do not think it's a problem with the format).

    
asked by anonymous 20.08.2018 / 20:40

1 answer

1

The problem is that on the chart you are using type: 'date' and the json data comes in string. So, in the controller you should put datetime in this format:

$obj = array(
      $reserva->nome, $reserva->sala, "2016-01-01 16:40:00", "2016-01-01 16:40:00"
);

Already in the view you use:

<script type="text/javascript">
    var data = {!!$data!!};
    //convertendo os tipos de string para date no javascript
    for (i = 0; i < data.length; i++) { 
        data[i][2] = new Date(data[i][2]);
        data[i][3] = new Date(data[i][3]);
    }
    ...
    //Codigo do chart
    ...
    dataTable.addRows(data);
    ...
</script>
    
22.08.2018 / 17:22