jasonej/enhanced-resources

This package is abandoned and no longer maintained. No replacement package was suggested.

Laravel's API Resources enhanced.

v1.0.0 2019-08-10 00:44 UTC

This package is auto-updated.

Last update: 2020-09-03 22:28:51 UTC


README

Laravel's API Resources enhanced.

Installation

$ composer require jasonej/enhanced-resources

Usage

Creating an Enhanced Resource

<?php

use Illuminate\Http\Resources\Json\JsonResource;
use Jasonej\EnhancedResources\EnhancedResource;

class Resource extends JsonResource
{
    use EnhancedResource;
}

Creating an Enhanced Collection

<?php

use Illuminate\Http\Resources\Json\ResourceCollection;
use Jasonej\EnhancedResources\EnhancedCollection;

class Collection extends ResourceCollection
{
    use EnhancedCollection;
}

Appending Attributes

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 Attributes

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"
}

Only Attributes

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"
}