New to Laravel and PHP so having a diffucult time with a small problem:
I’m stepping deep into a Collection and want to bring back nested items only that meet a certain (optional) date criteria.
Unfortunately, it isn’t working (at all). Here is my code:
public function getAnalyticsData(Request $request): JsonResponse { $data = collect(); $user = $request->user(); // Incoming request params $dataType = $request->input('data-type'); $startDate = $request->filled('start-date') ? strtotime($request->input('start-date')) : ''; $endDate = $request->filled('end-date') ? strtotime($request->input('end-date')) : ''; if ($dataType === 'orders') { $workgroupId = $request->input('workgroup-id'); $workgroups = Workgroup::where('id', $workgroupId)->with('analyticsOrders')->get(); $ordersData = $workgroups->map(function ($order) use ($startDate, $endDate) { return collect($order)->only(['analytics_orders'])->map(function ($item) use ($startDate, $endDate) { return collect($item)->when($startDate, function ($query) use ($startDate) { $query->where('created_at', '>=', $startDate); })->when($endDate, function ($query) use ($endDate) { $query->where('created_at', '<=', $endDate); }); }); }); $data->put('analyticsData', $ordersData); } else if ($dataType === 'integrations') { $data->put('analyticsData', $user); } // This is just to return something, please ignore return response()->jsonSuccess($data); }
While I have your attention, how can I only return the analytics_orders
array shown below (right now the data is very messy):
Advertisement
Answer
I guess you have mixed laravel collection with eloquent collection. Eloquent collection is on top of laravel collection not vice versa.
In laravel collection, when you use when()
method, a that collection will be passed to the closure function, there isn’t anything about laravel eloquent and $query
object. You have that collection instance and you should return something in your closure function.
So, edit your closure function as below and use return
return collect($item)->when($startDate, function ($collection) use ($startDate) { return $collection->where('created_at', '>=', $startDate); })->when($endDate, function ($collection) use ($endDate) { return $collection->where('created_at', '<=', $endDate); });