Level 29
Try
public function toArray($request)
{
return $this->module->id;
}
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hi.
Im a bit stuck on returning an api resource with a relationship and trying to get it to format the way I need.
Heres the UsersResource file::
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->unique_id,
'name' => $this->name,
'reference' => $this->reference,
'modules' => UserModulesResource::collection($this->modules),
];
}
UserModuleResource file::
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
$this->module->id
];
}
The layout im trying to get is ::
{
"id": 5f451a3c7827a,
"name": "Test User 1",
"reference": 1234567890,
"modules": [1,2,3]
},
Actual output ::
[
{
"id": "5f451a3c7827a",
"name": "Test User 1",
"reference": "1234567890",
"modules": [
[
1
],
[
2
],
[
2
]
]
}
]
How do I get it looking as the one im trying to replicate?
Many thanks
public function toArray($request)
{
return [
'id' => $this->unique_id,
'name' => $this->name,
'reference' => $this->reference,
'modules' => collect($this->modules)->pluck('id'),
];
}
Please or to participate in this conversation.