Create a gist now

Instantly share code, notes, and snippets.

@sixlive /0.README.md Secret
Last active Aug 29, 2017

What would you like to do?
Basic Resource Response Example

Resource Response

{
  "data": {
    "id": "0b1a798c-7e7e-46d1-8c4c-0c786730d36f",
    "name": null,
    "status": "Ready"
  }
}

Resource Collection Response

{
  "data": [
    {
      "id": "28122692-6c13-465e-a145-8c6ca540ba0d",
      "name": null,
      "status": "Ready"
    },
    {
      "id": "f3fc69f9-117b-4bb1-8445-bef9792a70ad",
      "name": null,
      "status": "Ready"
    }
  ]
}
<?php
namespace App\Http\Controllers\Api;
use App\Device;
use App\Http\Controllers\Controller;
use App\Http\Resources\DeviceResource;
class DeviceController extends Controller
{
public function index()
{
return DeviceResource::collection(Device::all());
// return fractal()
// ->collection(Device::all(), new DeviceTransformer())
// ->toArray();
}
public function store()
{
return DeviceResource::make(Device::register());
// return fractal()->item(Device::register(), new DeviceTransformer())->toArray();
}
public function show(Device $device)
{
return DeviceResource::make($device);
// return fractal()
// ->item($device, new DeviceTransformer())
// ->parseIncludes(request()->get('includes'))
// ->toArray();
}
public function destroy(Device $device)
{
$device->delete();
return response(null, 204);
}
}
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\Resource;
class DeviceResource extends Resource
{
public function toArray($request)
{
return [
'id' => $this->uuid,
'name' => $this->name,
'status' => $this->status->name,
];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment