Skip to content

Resource wrap when data column is present in database #56724

@challapradyumna

Description

@challapradyumna

Laravel Version

11.45.1

PHP Version

8.4.4

Database Driver & Version

No response

Description

I'm using laravel resources for responses and eloquent records are directly sent to the resource class for responses.

Issue: When returning single records using the resource class, if the database has a column named data the response is not wrapped. If the database does not have a column named data wrapping works which makes the responses inconsistent. Even though i've forced the resource to wrap with providing the $wrap property on the resource.

https://github.com/laravel/framework/blob/b8e2aa2527fb5601698e8021b3b205632ef2e4ba/src/Illuminate/Http/Resources/Json/ResourceResponse.php#L61C2-L73C6

protected function haveDefaultWrapperAndDataIsUnwrapped($data)
{
return $this->wrapper() && ! array_key_exists($this->wrapper(), $data);
}

protected function haveAdditionalInformationAndDataIsUnwrapped($data, $with, $additional)
{
return (! empty($with) || ! empty($additional)) &&
(! $this->wrapper() ||
! array_key_exists($this->wrapper(), $data));
}

Steps To Reproduce

Add a column called data in any database table. Return a single model object through the resource.

    public function show(Task $task)
    {
        return new TaskResource($task);
    }
<?php

namespace App\Http\Resources;

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

class TaskResource extends JsonResource
{

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

        ];
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions