Skip to content

Commit

Permalink
formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
taylorotwell committed May 1, 2020
1 parent 6fc3692 commit 965ff60
Showing 1 changed file with 18 additions and 43 deletions.
61 changes: 18 additions & 43 deletions eloquent-resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -312,6 +312,24 @@ By default, your outermost resource is wrapped in a `data` key when the resource
]
}

If you would like to use a custom key instead of `data`, you may define a `$wrap` attribute on the resource class:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
/**
* The "data" wrapper that should be applied.
*
* @var string
*/
public static $wrap = 'user';
}

If you would like to disable the wrapping of the outermost resource, you may use the `withoutWrapping` method on the base resource class. Typically, you should call this method from your `AppServiceProvider` or another [service provider](/docs/{{version}}/providers) that is loaded on every request to your application:

<?php
Expand Down Expand Up @@ -346,49 +364,6 @@ If you would like to disable the wrapping of the outermost resource, you may use

> {note} The `withoutWrapping` method only affects the outermost response and will not remove `data` keys that you manually add to your own resource collections.
If you would like to use a custom key instead of `data` in wrapping, you may use the `$wrap` attribute on the resource class:

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class User extends JsonResource
{
/**
* The "data" wrapper that should be applied.
*
* @var string
*/
public static $wrap = 'user';

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

It will wrap the data in JSON thus:

{
"user": {
"id": 1,
"name": "Eladio Schroeder Sr.",
"email": "therese28@example.com",
}
}

### Wrapping Nested Resources

You have total freedom to determine how your resource's relationships are wrapped. If you would like all resource collections to be wrapped in a `data` key, regardless of their nesting, you should define a resource collection class for each resource and return the collection within a `data` key.
Expand Down

0 comments on commit 965ff60

Please sign in to comment.