Search code examples
arraysjsonlaravelmorris.js

create array for morris js in laravel


I have difficulty loading certain data from the table to get a json array and include it into the morris js donut (example: https://codepen.io/ncarlucci/pen/JYxQBK)

I want to load from the table subscriber the different names from the column type and count them to get the following array:

[
    {value: 50, label: 'typename1'},
    {value: 25, label: 'typename2'},
    {value: 25, label: 'typename3'},
],

if I do it like this:

$subscriber = Subscribe::select('type')->get()->groupBy('type')
    ->map(function($subscribe){
        return $subscribe->count();
    })->toJson();

I get the follow output, but it is false:

{"company":1,"person":16,"user":6}

Solution

  • There might be a nicer way to handle your case, but since you didn't provide more informations about your model or database structure, this should work:

    $subscriber = Subscribe::select('type')->get()
        ->groupBy('type')
        ->map(function($subscribe, $label) {
            return ['value' => $subscribe->count(), 'label' => $label];
        })
        ->values()
        ->toJson();
    

    The key is to build the inner array element within the map function, then call values() to get rid of the unneded outer label left by the map function.

    If you need further explaination, just ask in the comments below