Basic Resource Response Example

By sixlive

Here is a brief example/preview of the new Laravel 5.5 resource responses. Taylor will be going into much greater detail about this at the Laracon EU conference (2017).

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

DeviceController.php

<?php

namespace App\Http\Controllers;

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);
    }
}

DeviceResource.php

<?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,
        ];
    }
}
Created 3 weeks ago | Updated 3 weeks ago

Comments