Using Request and Response Macros

We’ve already talked about the power of the collection macros. Now let’s take a look at the request and response macros as well to explore the possibilities that extending their functionality offers.

Using Request Macros

Since requests and responses are using the Illuminate\Support\Traits\Macroable trait, we can define macros that we can use later.

Let’s imagine, you have a process that you need to do over and over in different spots through your application. In this case, you might consider refactoring the flow to a reusable method, that you can use wherever you need.

To keep it simple, let’s stick to Adam Wathan’s idea, which allows our request to filter the parameters only to those that are not null. We can define the macro at the AppServiceProvider:

<?php

use Illuminate\Http\Request;

// ...

public function boot()
{
    Request::macro('filter', function () {
        return collect($this->all())->filter();
    });
}

From here, we can filter through our request data and the result will be a collection of the non-null elements. All you need to do, to call the filter() method on your request instance.

// input: ['email' => '[email protected]', 'name' => null]

$request->filter();

// result: ['email' => '[email protected]']

It’s nice, that we could extend the request itself and build a functionality that we can use without making our code a bit more messy all the time.

Using Response Macros

Response macros have the same concept like collection and request macros. Let’s say we have a functionality that we use over and over in our controllers. For example a specially formatted JSON data, where we separate the data itself and some other parameters. Originally we used this in our controller:

return response()->json([
    'status_code' => $statusCode,
    'user_id' => $userId,
    'data' => $data,
]);

As we see, it’s not a big mess at all, but still, we can refactor it a bit. As before, we can define the macro in our AppServiceProvider.

<?php

use Illuminate\Http\Response;

public function boot()
{
    Response::macro('toSpecialFormat', function ($code, $id, $data) {
        return Response::json([
            'status_code' => $code,
            'user_id' => $id,
            'data' => $data,
        ]);
    });
}

From now, we can use only one line instead of repeating the same code over and over again.

return response()->toSpecialFormat($statusCode, $userId, $data);

It’s nicer at once and also we follow DRY here, which helps us to keep the code cleaner. If you search around collection, string, request or response macros, you may find some very good ideas that you want to build in and use in your application.