Andy Holmes
Andy Holmes

Reputation: 8077

Laravel 5.1 format date array for chart.js data

Apologies, I can't upload my controller code right now but I'm hoping you can help with the info I can give you.

I'm using chart.js to plot a line graph of data. I'm passing the values from my controller for the data points and the date that matches the date point. The date labels are on the x axis and the data points are on the y axis.

In my view I'm receiving the following array from the controller:

["2015-06-01","2015-05-01","2015-04-01","2015-03-01","2015-02-01","2015-01-01"]

Which is then being encoded into JSON. Now, should I be attempting to format the date into something a bit more readable inside the controller or inside the view?

EDIT

This is my piece of code that's sending my weight data to my view:

$weight = Weight::where(compact('user_id', 'gecko_id'))->orderBy('weighed_date', 'desc')->take(7)->get()->reverse();

and then

return view('gecko.show')
            ->with('gecko', $gecko)
            ->with('dates', $weight->lists('weighed_date'))
            ->with('amounts', $weight->lists('gecko_weight'));

Upvotes: 3

Views: 1437

Answers (2)

Andy Holmes
Andy Holmes

Reputation: 8077

The only way I managed to achieve this was formatting the date inside my controller before sending it to my view. I will post code later when I'm not at work :)

Upvotes: 0

Mark Davidson
Mark Davidson

Reputation: 5513

I would say format it in ChartJS itself if your purely looking to change it as part of the presentation. If you look at this question we see that we can format our labels for data points using something like.

scaleLabel: function (valuePayload) {
    return Number(valuePayload.value).toFixed(2).replace('.',',') + '$';
}

now in your case you could maybe do something like

scaleLabel: function (value) {
    return moment(value).format("ddd, hA"); ;
}

to format date in a nice way. Making use of momentjs in this case.

Warning: Above is not tested I've never done this with ChartJS but in theory it should work.

Upvotes: 1

Related Questions