I am using Larapex charts for my laravel project but I cannot make the chart render when using a variable that contains my values retrieved from the database.
$userLogins = User::select(DB::raw("COUNT(*) as count")) ->whereYear('last_login_at', date('Y')) ->groupBy(DB::raw("Month(last_login_at)")) ->pluck('count');
The variable above retrives following values:
[1,1,3,1,1,1,1]
Which I then try to place within the chart
$chart = LarapexChart::areaChart() ->setTitle('Sales during 2021.') ->setSubtitle('UserLogins') ->addData('UserLogins', [$userLogins]) ->setXAxis(['January', 'February', 'March', 'April', 'May', 'June']);
But unfortunately the chart does not render the values.
Can anyone help me out?
Best regards.
Advertisement
Answer
The issue is that you are supplying values that the charts cannot understand. The result of pluck
is a Collection object and you have placed that object in an array, but it should be an array of numeric data. To extract just the count, you need to change this:
->addData('UserLogins', [$userLogins])
to this:
->addData('UserLogins', $userLogins->all())
Description of the all
method from the docs:
array all()
Get all of the items in the collection
So this will extract your actual array of counts ([1,1,3,1,1,1,1]
) from the Collection object.