This project has been archived. If you're curious, check out one of my latest courses:

If you work with JavaScript, check out the fetch use cases and JavaScript projects.

Thank you! — Jad Joubran

Response Macros

Re-usable custom responses.

Overview

Response macros are originally a feature in the Laravel framework.

REST APIs need to be consistent so we've provided you with 2 default response macros that will let you return success and error data from your endpoints.

PostsController.php
<?php

class PostsController
{
    public function get()
    {
        $posts = App\Post::all();

        return response()->success('posts', $posts);
    }

    public function update()
    {
        if ( !\Auth::user() ){
          return response()->error('Not Authorized', 401);
        }
    }

}

Success

The success interceptor, wraps your $results with the following structure:

Response
[
    'errors' => false,
    'data' => $results
]

Error

The error interceptor, returns an error message that can be directly used on the front-end, the error code as well as an additional info array:

Response
'message' => '422 error',
'errors' => [
    'message' => $message,
    'info' => $additional_info,
],
'status_code' => 422

The error interceptor's status code defaults to 422, unless overriden.

response()->error($error_message, $status_code = 422)