Laravel Response Macros for APIs
Jad Joubran has a great tutorial about how to use response macros when building an API with Laravel.
Dealing with APIs
Consistency is one of the most important aspects to consider when building an API. You often find yourself returning 2 types of responses; one for success and one for errors.
<?php class PostsController{ public function get(){ try { //some code }catch (Exception $e){ //error return [ 'errors' => true, 'message' => $e->getMessage() ]; } $posts = Post::get(); //success return [ 'errors' => false, 'data' => compact('posts') ]; } }
As you can see, we are returning error responses in a specific format, and success responses in a different format. Soon enough you’ll notice that you’re repeating this over and over again.
Using response macros
Response macros allow you to define a macro that can be called on the response() function.
We will create a new ResponseMacroServiceProvider and define a success and error macros inside the boot function:
<?php class ResponseMacroServiceProvider extends ServiceProvider { public function boot() { Response::macro('success', function ($data) { return Response::json([ 'errors' => false, 'data' => $data, ]);
Link:
This post is submitted by our members. Submit a new post.
Tags: Tutorials Laravel 5 Laravel 5.1 Intermediate Laravel 5.2