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

isadma's avatar

Convert API resource to array

I want to store data on Firestore. I need to send an array to Firestore. I have API resources and I wanted to use it.

My resource:

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'phone' => $this->phone,
            'addresses' => AddressResource::collection($this->addresses),
        ];
    }

Firestore:

    public function set(User $user){
        $userResource = new UserResource($user);
        $this->firestore->document($user->id)->set($userResource);
    }

The error:

Argument 1 passed to Google\Cloud\Firestore\DocumentReference::set() must be of the type array, object given...
0 likes
10 replies
kalemdzievski's avatar

You probably need to use the toArray method.

public function set(User $user) {
    $userResource = new UserResource($user);
    $this->firestore->document($user->id)->set($userResource->toArray());
}
isadma's avatar

I got this error:

Too few arguments to function App\Http\Resources\MobileApi\UserResource::toArray()
kalemdzievski's avatar

Wait, why are you using API resource to transform the user to array in order to store it in firestore? That's kinda not the purpose of API resources.

You don't wanna store the whole user using $user->toArray() for some reason ?

isadma's avatar

Because I use same format in all places. User model has also relations. I haven't added relation data to ApiResource yet. The same data I need to send to another place as a son. I didn't want to code twice. That's why I wanted to use ApiResource

isadma's avatar
isadma
OP
Best Answer
Level 2

This code works fine

public function set(User $user){
    $this->firestore->document($user->id)->set(json_decode((new UserResource($user))->toJson(), true));
}
2 likes
sanjitsingh's avatar

I am may be too late to respond. Here is the better way to get an array from resource:

UserResource::make($user)->resolve()
13 likes
phamduchuy552's avatar

@sanjitsingh That work with single instance I guess. With a collection of model, when manually return an array of property the following exception is thrown:

Property [<some_property>] does not exist on this collection instance.

Please or to participate in this conversation.