-
Notifications
You must be signed in to change notification settings - Fork 11.7k
Description
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.
framework/src/Illuminate/Http/Resources/Json/ResourceResponse.php
Lines 81 to 84 in b8e2aa2
| protected function haveDefaultWrapperAndDataIsUnwrapped($data) | |
| { | |
| return $this->wrapper() && ! array_key_exists($this->wrapper(), $data); | |
| } |
framework/src/Illuminate/Http/Resources/Json/ResourceResponse.php
Lines 94 to 99 in b8e2aa2
| 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,
];
}
}