Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

skoobi's avatar
Level 13

API Resources return as array

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

0 likes
3 replies
frankielee's avatar

Try

public function toArray($request)
{
    return   $this->module->id;
}
tykus's avatar
tykus
Best Answer
Level 104
public function toArray($request)
{
    return [
        'id' => $this->unique_id,
        'name' => $this->name,
        'reference' => $this->reference,
        'modules' => collect($this->modules)->pluck('id'),
    ];
}
1 like
skoobi's avatar
Level 13

Hi @frankielee.

Ive been staring at that for hours and hadn't spotted the brackets... Code blind or what.

Thank you for your help but this returned the wrong ids for some reason.

@tykus that worked perfectly.. thank you

Please or to participate in this conversation.