I am trying to assemble a graph of tasks per user/day, but I can't find how to order it easily.
I make the following queries to collect the tasks;
$tasksLastMonth = Task::where('user_id', Auth::user()->id)
->whereMonth('date', Carbon::now()->month)
->with('client')->get();
$tasksLastWeek = Task::where('user_id', Auth::user()->id)
->where('date', [Carbon::now()->startOfWeek(), Carbon::now()->endOfWeek()])
->with('client')->get();
On the other hand, I have two arrays with the days of the week and the month for the Xaxis of graph (are 2 graphs, one for week, and other for month)
$weekDays // [7,8,9,10,11,12,13]
$week // [1,2,3,4,.....,28]
Now, I need two arrays of the same length as the days of the week and month, for the Y axis, containing the number of tasks for each day. For example, if on day 8 there are 5 tasks it would look something like this:
$tasksInWeek = [0,5,0,0,0,0,0];
I also need other arrays for the number of clients for each day, but only the different ones. If one day there are 2 tasks for the same client, I only have to add 1 client that day.
I may be able to do it with just the query, but I can't find a way.
CodePudding user response:
This should work:
$groupedTasks = Task::where('user_id', Auth::user()->id)
->whereMonth('date', Carbon::now()->month)
->with('client')
->get()
->groupBy(function ($item) {
return $item->date->format('Y-m-d');
})
->map(function ($items, $date) {
return $items->unique('user_id');
});
The idea here is to, first, group the elements by the date (instead of using an integer) and then, on each group just keep the distinct users.
You can duplicate almost the same logic to get the data for the weekly chart.