How to make an API Resource in Laravel

APIs

Background

 Laravel has this concept of a Resource Controller, aka an Eloquent API Resource. This API translation layer sites between your eloquent resources and an API, e.g. a VueJS front-end API. They are incredibly useful as translation layers between Laravel and the API, and can be used to transform fields to make them API ready. Please note, the API Resources mentioned here is for outgoing translation only - and not from the API to Laravel. As usual the documentation for Eloquent API Resources is incredibly comprehensive and can be found here. To demonstrate their use, we include two real-world examples. 

Example 1 - Simple Currency Minor Unit Conversion

 The first example shows a simple numeric transformation. Currency data is stored as minor units in the database, but the front-end requires to have it in floating point format. As such, we have to divide all outgoing API requests with / 100. This could be done on the front-end, or even as a Accessor in the Eloquent resource, but this is a good example where API resources fulfills the perfect middleman role. 

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class OrderItemResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'         => $this->id,
            'order_id'   => $this->order_id,
            'product_id' => $this->product_id,
            'price'      => $this->price / 100,
            'quantity'   => $this->quantity,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,

        ];
    }
}
lang-php

Example 2 - Outputting Related Tables

 The second example show how to output an eloquent resource and it's related table. In this example OrderItemResource refers to the file above and is just another simple resource bound around a table. 

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class OrderResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'id'             => $this->id,
            'email'          => $this->email,
            'phone_number'   => $this->phone_number,
            'payment_method' => $this->payment_method,
            'total'          => $this->total / 100,
            'status'         => $this->status,
            'picked_up_at'   => $this->picked_up_at,
            'created_at'     => $this->created_at,
            'updated_at'     => $this->updated_at,
            'order_items'    => OrderItemResource::collection($this->order_items),
        ];
    }
}
lang-php

References