Transforming Laravel Request Data Using Middleware
Tags: middleware, laravel
Published: 2018-06-15 11:53:16

---
title: Transforming Laravel Request Data Using Middleware
published: true
tags: middleware,laravel
canonical_url: 
---

![](https://cdn-images-1.medium.com/max/384/1*CgNQ3ERM67ENaQTKSiG22A.jpeg)

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_](https://laravel.com/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:

{% gist https://gist.github.com/samolabams/ed67bc7782ace3f6cbd80959bcdee007 %}

On line 6, the _ParameterBag_ class was imported. Since laravel uses [Symphony HttpFoundation component](https://symfony.com/doc/current/create_framework/http_foundation.html) 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 _clean_Data (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 _Clean_Data 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.](https://gist.github.com/samolabams/ed67bc7782ace3f6cbd80959bcdee007)

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.](https://twitter.com/samolabams)

#### Thanks for reading