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

FelixINX's avatar

Array casting with index in API resource

Hi,

I am current casting my user_approval field to a JSON array using the following code:

protected $casts = [
    'user_approval' => 'array',
];

In artisan, my field is displayed with index and value:

>>> $a->user_approval 
=> [
     1 => true,
     2 => false,
     5 => false,
   ]

But when I use my API resource, only the value show up:

{
  "data": [
    {
      "approval": [
        true,
        false,
        false
     ],
     ...
   }
}

Here is the code for my resource:

class AnswerResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'approval' => $this->user_approval,
            'categoryId' => $this->category_id,
            'content' => $this->content,
            'id' => $this->id,
            'roundId' => $this->round_id,
            'user' => UserResource::make($this->user)->resolve()
        ];
    }
}

Is there a way to show index from a array casting inside a API resource?

Thank you

0 likes
12 replies
Sti3bas's avatar

@felixinx which version of Laravel you're using? It seems to be working in Laravel 6.

bugsysha's avatar

When encoding an array, if the keys are not a continuous numeric sequence starting from 0, all keys are encoded as strings, and specified explicitly for each key-value pair.

Strange. What happens when you do

json_encode($a->user_approval);
FelixINX's avatar

@bugsysha I get this:

"{"1":true,"2":false,"5":false}"

This is also what I have in my database.

@sti3bas I am on Laravel 6.2

bugsysha's avatar

Try replacing in AnswerResource

'approval' => $this->user_approval,

with

'approval' => [
1 => true,
2 => false,
5 => false, 
],
FelixINX's avatar

I still have the same result, without index.

I just updated to Laravel 6.10, no difference.

bugsysha's avatar

Does this help?

protected $casts = [
    'user_approval' => 'object',
];
1 like
Sti3bas's avatar

@felixinx yeah, I was wrong. It only works if you are calling toArray() method.

Workaround:

public function toArray($request)
{
   $approval = new stdClass;

   collect($this->user_approval)->map(function ($val, $key) use ($approval) {
      return $approval->{$key} = $val;
   });

   return [
      'approval' => $approval,
       //...
   ];
}

// Result: {"data":{"approval":{"1":true,"2":false,"5":false}}}
bugsysha's avatar
bugsysha
Best Answer
Level 61

@sti3bas No need for all that. He could only do

(object) $this->user_approval
bugsysha's avatar

Probably somewhere framework is only using values from that field and that is why keys are lost.

Please or to participate in this conversation.