1

I need to generate a pie chart whose output will be a representation of eloquent output.

My query is:

$data = MyModel::select('province_id', DB::raw('COUNT(id) AS cnt'))
    ->groupBy('province_id')
    ->get();

dd($data) gives me:

enter image description here

Then it is passed to blade view as:

return view('tool.charts', ['data' => $data]);

In my blade view (js code is embedded in <script> tag):

var datax = {!! json_encode($data) !!};

var chart = c3.generate({
    bindto: '#pie1',
    data: {
        columns: datax,
        type : 'pie',
    }
});

But this doesn't draw the pie chart. If I use hardcoded values, like:

var chart = c3.generate({
    bindto: '#pie2',
    data: {
        columns: [
            ['data1', 30],['data2', 140],['data3', 40],['data4', 170],
        ],
        type : 'pie',
    }
});

It shows the chart as expected.

UPDATE:

column was changed to json and still has no luck.

var chart = c3.generate({
    bindto: '#pie1',
    data: {
        json: datax,
        type : 'pie',
    }
});
Lakmal Premaratne
  • 1,159
  • 7
  • 18
  • 34

1 Answers1

0

First of all, pie chart is a bit different comparing to others (check here similar question).

For your case, I would suggest this:

  • In your controller, get data as json
public function myjson(Request $request){
    $data = MyModel::selectRaw('province_id, COUNT(*) AS cnt')
        ->groupBy('province_id')
        ->get();

    return response()->json($data->toArray());
}
  • define a route to access on this controller. Add this to your route:

Route::get('my/json', ['as'=> 'my.json', 'uses' =>’MyController@myjson']);

  • Then define your chart inside a blade using AJAX (Not passing variable from controller like you did)
<script language="JavaScript">
    $(document).ready(function () {
        $.ajax({
            type: "GET",
            url: '{{route('my.json')}}',
            data: "{}",
            contentType: "application/json",
            dataType: "json",
            async: "true",
            cache: "false",
            success: function (result) {
                OnSuccess(result);
            },
            error: function (xhr, status, error) {
                alert(error);
            }
        });
    });

    function OnSuccess(response) {
        var data = {};
        var lists = [];
        response.forEach(function (e) {

            lists.push(e.province_id);
            data[e.province_id] =  e.cnt;
        });

        var chart1 = c3.generate({
            bindto: '#pie1',
            data: {
                json: [data],
                type : 'pie',
                keys: {
                    value: lists
                }
            }
        });
    };

</script>
Rahman Rezaee
  • 1,943
  • 16
  • 24
4givN
  • 2,936
  • 2
  • 22
  • 51