DEV Community

Cover image for Creating Custom HTTP Responses with Laravel's Responsable Interface
Bilal Haidar
Bilal Haidar

Posted on

Creating Custom HTTP Responses with Laravel's Responsable Interface

Cover image taken from by

In Laravel, the Illuminate\Contracts\Support\Responsable interface provides a convenient way to return HTTP responses. This interface allows you to define a toResponse method that returns a Illuminate\Http\Response object.

Here's an example of how you can use the Responsable interface to create a custom response class for a Laravel route:

class ProfileImageUploaded implements Responsable
    protected $success;

    public function __construct($success)
        $this->success = $success;

    public function toResponse($request)
        if (!$this->success) {
            return new JsonResponse('Something went wrong!', 400);

        return new JsonResponse('Your profile image has been uploaded.');

Route::post('/profile-image', function (Requests\StoreProfileImageRequest $request) {
    $image = new Services\UserProfileImage($request->user());

    $success = $image->upload($request->image);

    return new ProfileImageUploaded($success);
Enter fullscreen mode Exit fullscreen mode

In this example, we have created a ProfileImageUploaded class that implements the Responsable interface and has a toResponse method. This method returns a JSON response indicating the status of the profile image upload.

To use the ProfileImageUploaded class in a route, we simply return an instance of it from the route closure. Laravel will automatically detect that the returned value is an instance of a class that implements the Responsable interface and will call the toResponse method to generate the HTTP response.

The Responsable interface is a convenient way to keep your routes focused on handling requests and delegate the responsibility of building HTTP responses to separate classes. It can also make your code easier to test and maintain by allowing you to isolate response-building logic into separate, reusable classes.

I hope this helps you understand how to use the Illuminate\Contracts\Support\Responsable interface in your Laravel applications!

Top comments (0)