Data model property in API Resource, how?

Posted 2 months ago by christiangerdes

Hi,

I have a model with a data field and I can't make it work with Laravel's API Resources. I suspect it has something to do with data being a reserved keywork?

Migration:

Schema::create('stores', function (Blueprint $table) {
            $table->increments('id');
            $table->string('title');
            $table->json('data');
            $table->softDeletes();
            $table->timestamps();
});

API Resource

class StoreResource extends Resource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'title' => $this->title,
            'data' => $this->data
        ];
    }
}

Controller

public function show(Store $store)
    {
        return new StoreResource($store);
    }

Response - Please note the response is not wrapped in data like the next response where the data key has been renamed to something else

{
    "id": 1,
    "title": "Vikleuniverset.dk",
    "data": {
        "key": "value",
        "john": "doe"
    }
}

Response with renamed data key

{
    "data": {
        "id": 1,
        "title": "Vikleuniverset.dk",
        "another": {
            "key": "value",
            "john": "doe"
        }
    }
}

How do I fix this to always wrap the response in a data property?

Please sign in or create an account to participate in this conversation.