In this episode, we're focusing on how to clean up and standardize the responses your Laravel API sends back, making life easier for both you (the developer) and whoever's consuming your API.
We kick things off by showing the usual way to return data from a controller — just dumping the model in the response. Then, we immediately start refining it by wrapping that data in a JSON response with a friendly message and even a try-catch to handle errors. But the big problem quickly becomes obvious: having to repeat basically the same response structure in every endpoint is tedious and error-prone.
To solve this, we get introduced to Laravel's Responsable
interface. This lets us build custom response objects that know how to turn themselves into a response, eliminating all that repeated boilerplate. First, we set up an ApiSuccessResponse
class, which accepts data, any metadata (like a success message), status codes (like 200 or 201), and optional headers. This means you can instantly update your response structure app-wide just by tweaking one class.
We don't stop there — errors need the same treatment. So we build an ApiErrorResponse
class, which handles exceptions smartly: in debug mode, detailed error info is included (super helpful while developing!); in production, only safe messages are shown to avoid leaking sensitive info. This class also takes custom status codes and headers, just like the success response.
By the end of the episode, you’ll have rock-solid, reusable response classes for both successes and errors, keeping your controllers clean, your API consistent, and making future updates a breeze.