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

untymage's avatar

Merge array to api resource outside of class

In api resources, How can i append a array outside of resource class ? for example:

class ThreadController extends Controller
{
    public function show(Thread $thread)
    {

    $customArray = ['append' => 'this array with key'];

        return new ThreadResource($thread);

    }
}

How to concat/merge$customArray to result of ThreadResource class ?

0 likes
8 replies
Sinnbeck's avatar

Why not pass it in through the constructor and append it inside?

$customArray = ['append' => 'this array with key'];

        return new ThreadResource($thread, $customArray);
Sinnbeck's avatar

Add this to the resource, and you can merge it in the toArray method

public function __construct($resource, $custom)
    {
        $this->resource = $resource;
        $this->custom = $custom;
    }
untymage's avatar

@sinnbeck Ok thanks, But i dont want to touch anything inside of class because there are only one place i would want to merge some variable.

Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Try this then

return array_merge((new ThreadResource($thread))->toArray(request()), $customArray) ;
untymage's avatar

ArgumentCountError : Too few arguments to function App\Http\Resources\ThreadResource::toArray(), 0 passed

Please or to participate in this conversation.