Laravel's API Resources enhanced.
$ composer require jasonej/enhanced-resources
<?php
use Illuminate\Http\Resources\Json\JsonResource;
use Jasonej\EnhancedResources\EnhancedResource;
class Resource extends JsonResource
{
use EnhancedResource;
}
<?php
use Illuminate\Http\Resources\Json\ResourceCollection;
use Jasonej\EnhancedResources\EnhancedCollection;
class Collection extends ResourceCollection
{
use EnhancedCollection;
}
The default behavior of API resources is to return the model's attributes:
<?php
$user = User::find(1);
Resource::make($user)->response();
{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"secret": "SUPERSECRET"
}
Appending an attribute allows you to dynamically append attributes via the model's underlying accessors.
Resource::make($user)->append(['name'])->response();
{
"id": 1,
"first_name": "John",
"last_name": "Doe",
"name": "John Doe",
"secret": "SUPERSECRET"
}
Excluding an attribute allows you to dynamically remove attributes from the resource's output.
Resource::make($user)->exclude(['id', 'secret'])->response();
{
"first_name": "John",
"last_name": "Doe"
}
The only method allows you to restrict a resource's output to only the provided set of attributes.
Resource::make($user)->only(['first_name', 'last_name'])->response();
{
"first_name": "John",
"last_name": "Doe"
}