Transforming Laravel Request Data Using Middleware

Samuel Tope
3 min readJun 14, 2018

--

There are times when we are required to format our form input values in order to make them more user friendly, like using input masking to format phone numbers (XXX-XXXX-XXXX) or currency (X,XXX,XXX). Depending on our data layer requirement. This kind of value may need to be normalized or transformed before been passed to the validator or saved in the database.

This tutorial assumes a fair amount of knowledge in Laravel. If you are new to laravel, you may want to check out the docs.

Our Approach

A method I found out lately involves creating a middleware class for transforming request data before the controller gets to handle the request. Since the middleware provides a convenient mechanism for filtering HTTP requests entering our application we can leverage on it to transform our data. Lets do this:

Step 1: Creating our middleware:

Create a new middleware with the make:middleware artisan command.

php artisan make:middleware TransformData

Open app/Http/Middleware/TransformData.php file and paste the code below:

On line 6, the ParameterBag class was imported. Since laravel uses Symphony HttpFoundation component behind the hood to handle HTTP layer concerns, we have access to Symphony ParameterBag Class (a container for key/value pairs) which is the store for our form data (request data). This class will enable us to manipulate our request and change the values to the desired format.

In addition to the middleware handle method, I added two other methods which are clean (line 34) and cleanData (line 45).

Let’s examine what these methods are doing.

Handle Method

public function handle($request, Closure $next)                           {
if ($request->isJson()) {
$this->clean($request->json());
} else {
$this->clean($request->request);
}
return $next($request);
}

The handle checks whether the incoming request is a json or regular request and passes the corresponding data to the clean method.

Clean Method

private function clean(ParameterBag $bag)                           {
$bag->replace($this->cleanData($bag->all()));
}

There are two methods of the ParameterBag class that is quite useful to us. The first is “all” which returns an array of parameters (in this case our form data) and the second method is “replace” which replaces the current parameters by a new set. The replace method expects an array as its argument. Simply meaning that we get our form data from the bag using the “all” method, we pass it to the cleanData method of our middleware to transform the data and cleanData returns its result to the ParameterBag “replace” method to replace the content of our request data. VOILLA!!!

CleanData Method

private function cleanData(array $data)                           
{
return collect($data)->map(function ($value, $key) {
if ($key == 'payment_amount') {
return preg_replace("/([^0-9])/", '', $value);
} else {
return $value;
}
})->all();
}

Our CleanData method receives the array returned from the all method, we then wrap the array in a collection class so that we can apply a custom function to modify each element. The array key stores each name of our form input and the array value stores the corresponding input value. Assuming we want to change the value of our payment_amount (The name of our input form field), get the value using the key and remove all non-digit characters. Return the data to the ParameterBag.

Apply middleware

Register this middleware in app/Http/Kernel.php file as “data.transform”:

...protected $routeMiddleware = [
...
'data.transform' => \App\Http\Middleware\TransformData::class,
];
...

Attach the middleware to your route or controller depending on the use-case.

Conclusion

In this article, we have seen how to transform our form request data with Laravel middleware, there are other use-cases for this method, Here’s the link to the github gist.

If you have a question that hasn’t been answered or you have a different perspective of this approach, feel free to drop in comments here or via Twitter.

Thanks for reading

--

--