I have a ReportCollection that collects a ReportResource. Inside that ReportResource there are users nested that also implement a resource collection:
'users' => ReportUserResource::collection($this->whenLoaded('users'))
and a job that is created with a resource:
'job' => new UserJobResource($this->whenLoaded('job')),
This all works great for my index method that gets the reports and returns them:
public function index($user_id)
{
$reports = Report::where('user_id', $user_id)
->with('users', 'job')
->orderBy('id', 'desc')
->paginate();
return new ReportCollection($reports);
}
Sample return of the above code:
{
"data": [
{
"id": 2,
"description": "Test",
"timestamp": {
"human": "1 day ago",
"original": "2020-07-06T17:42:00.000000Z"
},
"created_timestamp": {
"human": "1 day ago",
"original": "2020-07-06T17:43:36.000000Z"
},
"job": {
"id": 1,
"name": "Star Sydney",
"primary": "no"
},
"users": [
{
"name": "Michael",
"role": "Boss",
"type": ""
},
{
"name": "Jim",
"role": "Co-worker",
"type": "witness"
}
]
}
],
"links": {},
"meta": {}
}
I am creating a csv report of the exact same data and would like to also utilize this ReportCollection
. If I attempt with a similar code:
$reports = HarassmentReport::where('user_id', $request->user_id)
->with('users', 'job')
->orderBy('id', 'desc')
->get();
$reportCollection = new HarassmentReportCollection($reports);
I get a collection with more nested collections and not all the formatting that exists inside the resources. Ultimately, I want exactly what the resource returns, but in a fresh collection. I tried with:
ReportResource::collection($reports)->resolve()
which resolves the first layer, but does not resolve the nested UserJob and User resources. Looping through and resolving manually seems hackier than I would like, thus I am wondering if there is a clean way to access all of the resource formatting in all layers into one simple collection. I'm also hoping to leave out the meta data so that the end result is something like this:
[
{
"id": 2,
"description": "Test",
"timestamp": {
"human": "1 day ago",
"original": "2020-07-06T17:42:00.000000Z"
},
"created_timestamp": {
"human": "1 day ago",
"original": "2020-07-06T17:43:36.000000Z"
},
"job": {
"id": 1,
"name": "Star Sydney",
"primary": "no"
},
"users": [
{
"name": "Michael",
"role": "Boss",
"type": ""
},
{
"name": "Jim",
"role": "Co-worker",
"type": "witness"
}
]
}
]
I can return that exact payload with this code:
$reports = Report::where('user_id', $request->user_id)
->with('users', 'job')
->orderBy('id', 'desc')
->get();
$reportCollection = ReportResource::collection($reports);
return $reportCollection->collect();
but am not able to store it in a variable to then build a CSV file with.