Need help architecting or implementing a REST API? Book a call!

Guide

Responses

Learn how models are transformed into JSON responses.

Orion uses API Resources as a transformation layer between Eloquent models and actual responses that are returned to your API clients.

To allow these classes to be resolved automatically, they should follow the pattern: App\Http\Resources\<model>Resource or App\Http\Resources\<model>CollectionResource.

For example, if you have App\Models\Message model, the related resource class would be App\Http\Resources\MessageResource or App\Http\Resources\MessageCollectionResource.

If resource class names in your app do not follow this naming convention or if you just would like to be more explicit, set protected $resource or protected $collectionResource property on controller to a fully-qualified resource class name.

<?php

namespace App\Http\Controllers\Api;

use App\Models\Message;
use App\Http\Resources\CustomMessageResource;
use App\Http\Resources\CustomMessageCollectionResource;

class MessagesController extends ApiController
{
    /**
     * @var string $model
     */
    protected $model = Message::class;

    /**
     * @var string $resource
     */
    protected $resource = CustomMessageResource::class;

    /**
     * @var string $collectionResource
     */
    protected $collectionResource = CustomMessageCollectionResource::class;
}
There is a handy toArrayWithMerge method available on both Orion\Http\Resources\Resource and Orion\Http\Resources\CollectionResource classes - take a look there 😉

Copyright © 2019-2024 Aleksei Zarubin