Customize Laravel : Creating descriptive API response methodsDec 01, 2022
Have you ever wondered if we could write descriptive API response methods in Laravel?
As you can see, these helper functions are not only descriptive, but it also reduces our time by skipping the need to define the API JSON structure every time.
Building Descriptive API response methods
Creating Response Macros
We can add our custom macros directly into the AppServiceProvider file. However, it would be wise if we can have a separate provider for that. So, let's create a new one like below.
php artisan make:provider ResponseServiceProvider
after creating our service provider, kindly add it to providers array in config/app.php file
As you can see on the above code, you can always override the default error message by passing your custom error message to each method.
Now that we've our macros in place, let's make use of them.
That's it. Now we have clean and straightforward response methods. We need not worry about the API structure and in case we're going to change it in the future, the one place we might change is only our ResponseServiceProvider and our entire system will be updated automatically.