dedoc/scramble

Wrong Attribute Margining on Response Example

kalimulhaq opened this issue · 3 comments

I have a scenario where I have a BaseResource that holds some common fields which are part of every model, and I want these to be included in every API resource that extends this base resource. See the following example code:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class BaseResource extends JsonResource
{

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return [
            'created_at' => $this->whenHas('created_at'),
            'updated_at' => $this->whenHas('updated_at'),
        ];
    }

}

<?php

namespace Domains\Organization\Http\Resources;

use App\Http\Resources\BaseResource;
use Illuminate\Http\Request;

class DivisionResource extends BaseResource
{

    /**
     * Transform the resource into an array.
     *
     * @return array<string, mixed>
     */
    public function toArray(Request $request): array
    {
        return array(
            'id' => $this->id,
            'name' => $this->whenHas('name'),
            ...parent::toArray($request),
        );

    }
}

The child resource class includes the fields from the parent resource class inside array methods. This is working perfectly, and the actual response includes those fields. However, the Response Example shows incorrect merging. See the screenshot.

image image

Hey @kalimulhaq!
Gotcha. Will fix. By the way, I can see the casing in the real API response is also different: while in the code base it is 'created_at', in the real response it is 'createdAt'. How that is implemented?

@romalytvynenko

Thank you for your response. I have found a fix for now. The Scramble is working perfectly with the built-in merge function in the Resource class.

public function toArray(Request $request): array
{
    return [
        'id' => $this->id,
        'name' => $this->whenHas('name'),
        $this->merge(parent::toArray($request)),
    ];
}

Regarding the transformation of keys, we have a requirement to use camelCase for the API parameters while keeping the database column names in snake_case. To achieve this, we're using middleware to handle the transformation.

fixed in #506