Keeping API response consistent becomes really difficult sometimes specially if you have just started or you are in learning phase. A lot of articles are present online and each of them looks right but Today i want to tell you the easiest way to do that.
If you would like to watch me doing this then here is the tutorial video for that.
So let’s begin…
We are using a third party package here, So let’s pull the package first using composer.
composer require marcin-orlowski/laravel-api-response-builder
Now to make it easier to use the package, let’s declare some functions in base controller file for handling successful and error case.
Now we need a way a file to store our api codes. For this let’s create app/ApiCode.php file and declare some constants like this.
Now for each of the API code we need to store messages. So let’s create a new file resources/lang/en/api.php and add these messages.
We just need to map Api Code with these messages now. For that we’ll create config/response_builder.php file.
That’s it! We can now use the functions written in base controller.
Like this…
if (! $token = auth()->attempt($credentials)) {
return $this->respondUnAuthorizedRequest(ApiCode::INVALID_CREDENTIALS);
}
Hope you like it!
Let me know your views about this approach.