I'm trying to build an API in Laravel 9 and want data from a pivot table.
I want to retrieve all instances, whether they have sessions assigned to them or not, and display the sessions where relevant.
I currently have a table of instances and a table of sessions - each instance can each many sessions, and each session can belong to multiple cases.
Instance Model
public function sessions() {
return $this->belongsToMany(Session::class)->using(InstanceSession::class)->withPivot(['date', 'zoom_room_id', 'trainer_id']);
}
Session Model
function instances() {
return $this->belongsToMany(Instance::class);
}
If I put this in my Resource:
public function toArray($request)
{
return [
'courseName' => $this->course->name,
'cohort' => $this->cohort->name,
'sessions' => $this->sessions
];
}
It outputs this object for each session along with the data for the instance.
{
"id": 10,
"name": "eos totam corporis aut",
"review_due": "2022-10-11",
"review_status": "Embedding",
"slides": "http://www.schimmel.com/",
"trainer_notes": "http://www.roberts.com/vero-asperiores-voluptatum-facilis-aut-omnis-eos.html",
"created_at": "2022-11-01T17:00:24.000000Z",
"updated_at": "2022-11-01T17:00:24.000000Z",
"pivot": {
"instance_id": 1,
"session_id": 10,
"date": "2023-01-06",
"zoom_room_id": 1,
"trainer_id": 17
}
}
How do I access that pivot object and its relationships to get the data I want?
NB. I have tried the pivot methods and whenLoaded methods from the Laravel docs, and this doesn't seem to give me anything.