Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/Illuminate/Http/Resources/Json/JsonResource.php
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ class JsonResource implements ArrayAccess, JsonSerializable, Responsable, UrlRou
*/
public $wrapper = null;

/**
* Indicates if the wrapper has been set on this instance.
*
* @var bool
*/
public $wrapperSet = false;

/**
* The "data" wrapper that should be applied.
*
Expand All @@ -65,8 +72,6 @@ class JsonResource implements ArrayAccess, JsonSerializable, Responsable, UrlRou
public function __construct($resource)
{
$this->resource = $resource;

$this->withWrapper(static::$wrap);
}

/**
Expand Down Expand Up @@ -218,6 +223,7 @@ public function withResponse(Request $request, JsonResponse $response)
public function withWrapper(?string $value)
{
$this->wrapper = $value;
$this->wrapperSet = true;

return $this;
}
Expand Down
2 changes: 1 addition & 1 deletion src/Illuminate/Http/Resources/Json/ResourceResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ protected function haveAdditionalInformationAndDataIsUnwrapped($data, $with, $ad
*/
protected function wrapper()
{
return $this->resource instanceof JsonResource
return $this->resource instanceof JsonResource && $this->resource->wrapperSet
? $this->resource->wrapper
: get_class($this->resource)::$wrap;
}
Expand Down
23 changes: 23 additions & 0 deletions tests/Integration/Http/ResourceTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,29 @@ public function testResourceCollectionCanSetWithoutWrapper()
]);
}

public function testResourcesCanSetWithoutWrappingAfterCreatingInstance()
{
Route::get('/', function () {
$resource = new PostResource(new Post([
'id' => 5,
'title' => 'Test Title',
]));

$resource::withoutWrapping();

return $resource;
});

$response = $this->withoutExceptionHandling()->get(
'/', ['Accept' => 'application/json']
);

$response->assertJson([
'id' => 5,
'title' => 'Test Title',
]);
}

public function testResourcesMayHaveOptionalValues()
{
Route::get('/', function () {
Expand Down