Docs

Response Macros

Response macros are originally a feature in the Laravel framework.

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

<?php

class PostsController
{
    public function get()
    {
      	$posts = App\Post::all();  
      
    		return response()->success('posts', $posts);
    }
  
}
<?php

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

Note that even validation errors through $this->validate($request, []) will return the same error format as response()->error() but with a status code of 422 (Unprocessable Entity).

This means that you can always expect the same response format for all success responses.
And another unified response format for all error responses (including validations).

This repository takes advantage of consistency, by configuring Restangular to show validation errors in a Toast message.

Of course, there are API test helpers that are provided so you can easily assert the correct response macro is being used (also makes sure your return types are consistent).
For example ->seeApiSuccess(), ->seeValidationError(), ->seeApiError(401).

🚧

Validation response

If you plan on modifying the error response macro, you'd need to apply a fix in App\Http\Controllers\controller.php which is the base controller.

Prefer a blogpost?
https://blog.jadjoubran.io/2016/03/27/laravel-response-macros-api/