DEV Community

Samuel Tope
Samuel Tope

Posted on • Originally published at Medium on

Transforming Laravel Request Data Using Middleware

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
Enter fullscreen mode Exit fullscreen mode

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 _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);
}
Enter fullscreen mode Exit fullscreen mode

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()));
}
Enter fullscreen mode Exit fullscreen mode

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();                           
}
Enter fullscreen mode Exit fullscreen mode

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_** _,_  
];
...
Enter fullscreen mode Exit fullscreen mode

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

Top comments (4)

Collapse
 
ra1da35ma profile image
Rasheed Rahman

How about I want to transform the request key

For example; Data is coming from Angular app as _transaction_id because of getter/setter in typescript hence I need a middleware to remove the initial underscore in all request keys

Collapse
 
samolabams profile image
Samuel Tope • Edited

Yeah, you can do that too, just change the cleanData function of your middleware


/**
    * Check the parameters and remove the initial underscore
    *
    * @param  array  $data
    * @return array
    */
    private function cleanData(array $data)
    {
        return collect($data)->mapWithKeys(function($value, $key) {
                if ($key !== '_token') {
                    $key = preg_replace("/(^_)/", '', $key);
                }
                return [$key => $value];
        })->all();
    }

What am doing here is to remove the initial underscore if the request key is not '_token', since laravel needs that for csrf (in case you are using the web route group). Sorry for the late response. Let me know if it helps.

Collapse
 
vahidalvandi profile image
vahid alvandi

thank you work fine

Collapse
 
sivaramadurai profile image
sivaramadurai

Can we add the modified parameters to bag instead of replacing them.