Digging Deeper

Responses

The response is the way you have to manipulate the API's output for each model.
The response is the final piece of the API and should be used judiciously, as it can override all the underlying logic of Laravel Rest API.

Defining Responses

By default, Rest responses are stored in the app/Rest/Responses directory of your application. You may generate a new Response by using the rest:response Artisan command:

php artisan rest:response UserResponse

You are now free to modify the map method from your new Response:

/**
 * This maps on each model returned by the API, use it at your ease.
 *
 * @var \Illuminate\Database\Eloquent\Model $model
 * @var array $responseModel
 *
 * @return array
 */
protected function map(\Illuminate\Database\Eloquent\Model $model, array $responseModel) : array {
    return $responseModel;
}

The $model represents the original model, whereas $responseModel is the response that would typically be initiated by Laravel Rest Api.

Responses should be considered as a final resort for leveraging the API. In most cases, they may not be necessary.

Registering Responses

You now have to specify the Response within the corresponding Resource file.

UserResource.php
/**
 * The reponse the entry corresponds to.
 *
 * @var class-string<Response>
 */
public static $response = App\Rest\Responses\UserResponse::class;

Copyright © 2024