I have this query where I get my data by using pagination:
$data = Mymodel::orderBy('id','desc')->paginate(10);
And I have no problems to display the data in a bootstrap table with its pagination links within a blade file:
<table class="table table-bordered table-responsive table-striped table-hover table-condensed">
<thead>
<tr>
<th>id</th>
<th>value1</th>
<th>value2</th>
</tr>
</thead>
<tbody>
@foreach($data as $row)
<tr>
<td>{{ $row->id }}</td>
<td>{{ $row->value1 }}</td>
<td>{{ $row->value2 }}</td>
</tr>
@endforeach
</tbody>
</table>
{{ $data->links() }}
Now when setting up a google line chart:
@section('js')
{{--Google charts--}}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart'],'language': 'es'});
google.charts.setOnLoadCallback(drawLinechart);
function drawLinechart()
{
var record = {!!$data!!};
var data = new google.visualization.DataTable();/*http://stackoverflow.com/a/22640426/1883256*/
var rowsnumber = record.length;
//Declaring the column names
data.addColumn('number', 'ID');
data.addColumn('number', 'Value1');
data.addColumn('number', 'Value2');
//Filling each row. Ref:http://stackoverflow.com/a/7861051/1883256
$.each(record, function(k, v) {
//display the key and value pair
//console.log(k + ' is ' + v.id);
data.addRow([v.id,parseInt(v.value1),parseInt(v.value2)]);
});
var options = {
title: 'Data last '+ rowsnumber +' rows',
//curveType: 'function',
backgroundColor: { fill:'transparent'},
height: 500,
legend: { position: 'bottom' },
};
var chart = new google.visualization.LineChart(document.getElementById('linechart'));
chart.draw(data, options);
}
</script>
{{-- end of Google charts--}}
@endsection
This does not work because it turns out that paginate inserts html code for the pagination links, since I get the following error:
Uncaught SyntaxError: Unexpected token <
And this is because the $data
outputs:
var record = <ul class="pagination">
... and so on ... instead of the Eloquent's collection. It outputs actually a LengthAwarePaginator
.
Then how do I access the data ($row->id
,$row->value1
,$row->value2
)
right in the javascript section?
On the other hand, this does work if I get the data through another query variable:
$datachart = Mymodel::orderBy('id','desc')->take(30)->get();
which is in fact a collection. In other words, this is working:
var record = {!!$datachart!!};
But what I really want is to chart the data along with the pagination so that in every page I can output the corresponding values in the linechart.
Any ideas on how to access the collection data in javascript right from a LengthAwarePaginator?
Workaround: I get another collection with the same query but without the pagination and now it is working.