<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Samuel Tope</title>
    <description>The latest articles on DEV Community by Samuel Tope (@samolabams).</description>
    <link>https://dev.to/samolabams</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F49843%2F796244ee-668e-4c3e-90ef-9731abcfa02b.jpg</url>
      <title>DEV Community: Samuel Tope</title>
      <link>https://dev.to/samolabams</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/samolabams"/>
    <language>en</language>
    <item>
      <title>Reducing Your  Array The Right Way</title>
      <dc:creator>Samuel Tope</dc:creator>
      <pubDate>Mon, 22 Oct 2018 16:31:22 +0000</pubDate>
      <link>https://dev.to/samolabams/reducing-your--array-the-right-way-787</link>
      <guid>https://dev.to/samolabams/reducing-your--array-the-right-way-787</guid>
      <description>

&lt;h3&gt;Reducing Your Array The Right Way&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--QGdwoYGM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AvXkJ89ppSS1eddnK2stWOw.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--QGdwoYGM--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn-images-1.medium.com/max/1024/1%2AvXkJ89ppSS1eddnK2stWOw.jpeg" alt=""&gt;&lt;/a&gt;Image credits: Pixabay&lt;/p&gt;

&lt;p&gt;One of the benefits of Javascript as a language is that it allows us to write functional style of programming, that is, we write programs by composing functions which describe actions (what should happen) and abstracts the processes (how it should happen). This style of programming is possible in javascript because functions are first-class citizens, they are data and can be passed around in your application like variables.&lt;/p&gt;

&lt;h4&gt;Pure Functions&lt;/h4&gt;

&lt;p&gt;One of the core tenet of functional programming is writing pure functions. Pure functions are functions that have no free variables, i.e all its variables comes from its arguments, thereby making it return the same value for the same arguments, It has no side-effects on the program because it does not change the program state.&lt;/p&gt;

&lt;p&gt;If a pure function needs to mutate or modify any variable(arguments) passed to it, it will create a copy, modify and return the copy, leaving the original variable untouched. This is called immutability. The essence of functional programming is using functions to transform data from one form to another, like i mentioned earlier, these data are copied before being transformed thereby leaving the original data intact. This improves readability, testability and correctness of our program.&lt;/p&gt;

&lt;h4&gt;Array.prototype.reduce And Array.prototype.reduceRight&lt;/h4&gt;

&lt;p&gt;Array is a basic data structure in javascript there are several operations we can perform on an array by applying functions to it. We will be taking a look at two of these functions in this article. They are called &lt;strong&gt;reduce&lt;/strong&gt; (Array.prototype.reduce) and &lt;strong&gt;reduceRight&lt;/strong&gt; (Array.prototype.reduceRight). &lt;em&gt;What these functions does is to process an array by iterating over its elements and building up a single value that is returned based on a specified criteria.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;reduce()&lt;/em&gt; and &lt;em&gt;reduceRight()&lt;/em&gt; works in the same way except that &lt;em&gt;reduce()&lt;/em&gt; starts from the first item in the array to the last while &lt;em&gt;reduceRight()&lt;/em&gt; starts from the last item to the first.&lt;/p&gt;

&lt;p&gt;Both &lt;em&gt;reduce()&lt;/em&gt; and &lt;em&gt;reduceRight()&lt;/em&gt; accept two arguments, &lt;em&gt;a function that performs the reduction operation (a reducer) and an optional initial value with which the reducer starts its operation.&lt;/em&gt; The reducer accepts four arguments: the previous item (also called the accumulated value), the current item, the current item’s index and the array itself. The first two arguments of the reducer is commonly used. The value returned from each iteration (the accumulated value) is passed to the next iteration as the first argument.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;The reduce() and reduceRight() uses a reducer, the reducer is the function that does the actual calculation on each iteration.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;Examples&lt;/h4&gt;

&lt;p&gt;Lets use a basic example to illustrate how reduce works, we are going to sum up the elements of an array using the reduce function.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [2,4,6,7,8];
let sum = numbers.reduce((acc, cur) =&amp;gt; {
 return acc + cur;
});
console.log(sum); // 27
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;There are five elements in the numbers array, the reducer will iterate through the elements using the first value (2) as the intial accumulator (acc). Lets see what each value looks like for each iteration.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;First iteration =&amp;gt; acc = 2, cur = 4, acc + cur = 6
Second iteration =&amp;gt; acc = 6, cur = 6, acc + cur = 12
Third iteration =&amp;gt; acc = 12, cur = 7, acc + cur = 19
Fourth iteration =&amp;gt; acc = 19, cur = 8, acc + cur = 27
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;if a second argument is passed to the reduce function like this&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [2,4,6,7,8];
let sum = numbers.reduce((acc, cur) =&amp;gt; {
 return acc + cur;
}, **20** );

console.log(sum); // 47
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;It will be the first argument to the reducer and the iteration will occur five times instead of four like this:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;First iteration =&amp;gt; acc = 20, cur = 2, acc + cur = 22
Second iteration =&amp;gt; acc = 22, cur = 4, acc + cur = 26
Third iteration =&amp;gt; acc = 26, cur = 6, acc + cur = 32
Fourth iteration =&amp;gt; acc = 32, cur = 7, acc + cur = 39
Fifth iteration =&amp;gt; acc = 39, cur = 8, acc + cur = 47
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;The best practice is to initialize the reduce function to a reasonable default by providing a value as the second argument of the reduce function.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;To find the largest number in an array using the reduce function:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [20,22,50,60,12];
const largestNumber = numbers.reduce((max, num) =&amp;gt; {
 console.log(`${num} &amp;gt; ${max} is ${num &amp;gt; max}`); 
 return (num &amp;gt; max) ? num : max
}, 0);

console.log(largestNumber); // 60
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In the above example, the max variable was initialized to 0, on each iteration, the reducer compares the current max value with the current element (num) and returns the greater of the two values, the returned value is assigned to the max variable and its used for the next iteration.&lt;/p&gt;

&lt;p&gt;To remove duplicate elements in array using the reduce function:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let numbers = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];

let distinctNumbers = numbers.reduce((distinct, num) =&amp;gt; {
 return (distinct.indexOf(num)) !== -1 ? distinct : [...distinct, num];
}, []);

console.log(distinctNumbers); // [1,2,3,5,4]
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Note that the reduce function was initialized to an empty array because we are expecting an array as our result, this is the reasonable default. What the reducer is doing in this example is to check if a number already exists in the initialized array, add it if it doesn’t exist, and return the array. The spread operator is used here.&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Lets have one more example to illustrate &lt;em&gt;reduceRight()&lt;/em&gt;. Assuming we need to perform an operation that has a right to left precedence, like an arithmetic operation. Lets see an example below:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Compute 3^(3^2)
// We calculate (3 ^ 5) first, assuming the result is n, we then calculate (2 ^ n) to get the final answer.

let numbers = [3,3,2];
let answer = numbers.reduceRight((ans, num) =&amp;gt; {
 return Math.pow(num, ans);
});

console.log(answer); // 19683
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;In the example below, the reducer starts from the right (2), In the first iteration, the calculation will be (3²) which is 9, the second iteration will be (3⁹) which is 19683.&lt;/p&gt;

&lt;h4&gt;Conclusion&lt;/h4&gt;

&lt;p&gt;I have just shown you a little of the capabilities of &lt;em&gt;reduce()&lt;/em&gt; and &lt;em&gt;reduceRight()&lt;/em&gt;, They have more use-cases than what we have treated here. To learn more, &lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce"&gt;check out the MDN docs&lt;/a&gt;. &lt;a href="https://css-tricks.com/understanding-the-almighty-reducer/"&gt;Sarah drasner also wrote an article on css-tricks&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Thanks for Reading&lt;/p&gt;


</description>
      <category>purefunction</category>
      <category>javascript</category>
      <category>reducer</category>
      <category>arraymethods</category>
    </item>
    <item>
      <title>Understanding Vuejs Lifecycle hooks</title>
      <dc:creator>Samuel Tope</dc:creator>
      <pubDate>Tue, 21 Aug 2018 19:50:43 +0000</pubDate>
      <link>https://dev.to/samolabams/understanding-vuejs-lifecycle-hooks-5ejk</link>
      <guid>https://dev.to/samolabams/understanding-vuejs-lifecycle-hooks-5ejk</guid>
      <description>

&lt;p&gt;A component in Vuejs has a lifecycle which is being managed by Vue itself when it creates the component, mounts the component to the DOM, updates the component and destroy the components. In order words, Each component has what is known as lifecycle events — its birth, life events like changes and death_._ We can tap into key moments in that lifecycle by implementing one or more lifecycle hooks that gets called by Vue itself thereby giving us the opportunity to add our own code at specific stages of a component lifetime.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Vue has eight lifecycle hooks, and the key to remembering them is to know that four of them are event that get triggered indicating that the actual event will happen. They start with “before” prior to the actual hooks and are fired before the actual hooks.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Lets see these hooks in action.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;beforeCreate&lt;/strong&gt;  — This is the first hook that gets called after the Vue instance has been initialized. At this stage, data observation (reactivity), events, computed properties and watchers are yet to be set up. Therefore , we cannot interact with any parts of the component.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
export default {
  data() {
    return {
      counter: 0
    }
  },

  beforeCreate() {
    console.log('I am the first hook to get called!');
    console.log(`You can see that my data property is ${typeof this.counter}`); // undefined
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Created&lt;/strong&gt;  — This hook is called after the instance is created. At this stage, the instance has finished processing, data observation (reactivity), computed properties, methods, watchers and event callbacks have been set up. You can’t interact with the DOM at this stage because your component has not been mounted. The $el property is not also available yet.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
export default {
  data() {
    return {
      counter: 0
    }
  },

  created() {
    console.log('I am the created hook.');
    console.log(`You can now see that my data property is ${typeof this.counter}`);
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;beforeMount &lt;/strong&gt; — At this stage, the template is compiled, either from the template or render options, or from the outerHTML of the element that Vue was initialized to. The template isn’t rendered yet and the $el method doesn’t exist either. Please note that this hook is not called during sever-side rendering.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
export default {
  beforeMount() {
    console.log(`I am ready to be rendered.!`)
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Mounted &lt;/strong&gt; — Called after the instance has been mounted, where el property is replaced by the newly created vm.$el. If the root instance is mounted to an in-document element, vm.$el will also be in-document when mounted is called. The component becomes fully functional after the mounted hook is called and we can fully interact with it.&lt;/p&gt;

&lt;p&gt;One thing to take note of is that the mounted hook doesn’t guarantee that the element has been added to DOM. To execute a code that is DOM dependent at this stage, put the code inside a callback method to the Vue.nextTick() function (&lt;em&gt;Vue.nextTick() defers its callback to be executed after the next DOM update cycle&lt;/em&gt;). See the example below:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;p&amp;gt;I'm text inside the component.&amp;lt;/p&amp;gt;
&amp;lt;/template&amp;gt;

&amp;lt;script&amp;gt;
export default {
  mounted() {
    // Element might not have been added to the DOM yet
    this.$nextTick(() =&amp;gt; {
        // Element has been definitely added to the DOM
       console.log(this.$el.textContent); // I'm text inside the component.
    }
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;beforeUpdate&lt;/strong&gt;  — It is called anytime changes are made to our data and the DOM needs to be updated, right before the DOM is patched. This is a good place to access the existing DOM before an update, e.g. to manually remove an added event listeners. This hook is not called during server-side rendering, because only the initial render is performed at server-side.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
export default {
  data() {
    return {
      counter: 0
    }
  },

  beforeUpdate() {
    console.log(this.counter) // Logs the counter value every second, before the DOM updates.
  },

  created() {
    setInterval(() =&amp;gt; {
      this.counter++
    }, 1000)
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Updated&lt;/strong&gt;  — hook is fired after a change has been made. The component’s DOM would have been updated when this hook is called, so you can perform DOM-dependent operations here. However, in most cases you should avoid changing state inside the hook. To react to state changes, it’s usually better to use a &lt;a href="https://devdocs.io/vue~2/api/index#computed"&gt;computed property&lt;/a&gt; or &lt;a href="https://devdocs.io/vue~2/api/index#watch"&gt;watcher&lt;/a&gt; instead.&lt;/p&gt;

&lt;p&gt;Note that updated does &lt;strong&gt;not&lt;/strong&gt; guarantee that all child components have also been re-rendered. If you want to wait until the entire view has been re-rendered, you can use &lt;a href="https://devdocs.io/vue~2/api/index#vm-nextTick"&gt;vm.$nextTick&lt;/a&gt; inside of updated:&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;template&amp;gt;
  &amp;lt;p ref="dom-element"&amp;gt;{{counter}}&amp;lt;/p&amp;gt;
&amp;lt;/template&amp;gt;
&amp;lt;script&amp;gt;
export default {
  data() {
    return {
      counter: 0
    }
  },

  updated() {
    // Fired every second, should always be true
    console.log(+this.$refs['dom-element'].textContent === this.counter)
  },

  created() {
    setInterval(() =&amp;gt; {
      this.counter++
    }, 1000)
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;beforeDestroy&lt;/strong&gt;  — Called right before a Vue instance is destroyed. At this stage the instance is still fully functional. You can perform necessary cleanups here. Please note that this hook is not called during sever-side rendering.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
export default {
  data() {
    return {
      counter: 0
    }
  },

  beforeDestroy() {
    // Clean up the counter.
    // (In this case, effectively nothing)
    this.counter = null
    delete this.counter
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Destroyed&lt;/strong&gt;  — Called after a Vue instance has been destroyed. When this hook is called, all directives of the Vue instance have been unbound, all event listeners have been removed, and all child Vue instances have also been destroyed. Please note that this hook is not called during sever-side rendering.&lt;/p&gt;



&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
import DestroyerNotifierService from './notifier'

export default {
  destroyed() {
    console.log(this) // There's practically nothing here!
    DestroyerNotifierService.informThem('Component destroyed')
  }
}
&amp;lt;/script&amp;gt;
&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;All lifecycle hooks automatically have their this context bound to the component instance, so that you can access data, computed properties, and methods. This means &lt;strong&gt;you should not use an arrow function to define a lifecycle method&lt;/strong&gt; (e.g. created: () =&amp;gt; this.fetchTodos()). The reason is arrow functions bind the parent context, so this will not be the Vue instance as you expect and this.fetchTodos will be undefined.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In order words, arrow functions does not have their own value of &lt;em&gt;this&lt;/em&gt;. The value of this in an arrow function is inherited from the enclosing (lexical) scope. So, you cannot use them inside a hook.&lt;/p&gt;

&lt;h3&gt;Conclusion&lt;/h3&gt;

&lt;p&gt;In this article, we have learnt about Vuejs Component lifecycle and their applications.&lt;/p&gt;

&lt;h4&gt;Thanks for reading.&lt;/h4&gt;


</description>
      <category>componentlifecycle</category>
      <category>vue</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Transforming Laravel Request Data Using Middleware</title>
      <dc:creator>Samuel Tope</dc:creator>
      <pubDate>Thu, 14 Jun 2018 18:38:09 +0000</pubDate>
      <link>https://dev.to/samolabams/transforming-laravel-request-data-using-middleware-2k7j</link>
      <guid>https://dev.to/samolabams/transforming-laravel-request-data-using-middleware-2k7j</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffuo8sxcngf4520w2u3j3.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffuo8sxcngf4520w2u3j3.jpeg" width="384" height="131"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;This tutorial assumes a fair amount of knowledge in Laravel. If you are new to laravel, you may want to&lt;/em&gt; &lt;a href="https://laravel.com/docs/" rel="noopener noreferrer"&gt;&lt;em&gt;check out the docs&lt;/em&gt;&lt;/a&gt;&lt;em&gt;.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  &lt;strong&gt;Our Approach&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;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:&lt;/p&gt;

&lt;h3&gt;
  
  
  Step 1: Creating our middleware:
&lt;/h3&gt;

&lt;p&gt;Create a new middleware with the &lt;em&gt;make:middleware&lt;/em&gt; artisan command.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;php artisan make:middleware TransformData
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Open &lt;em&gt;app/Http/Middleware/TransformData.php&lt;/em&gt; file and paste the code below:&lt;/p&gt;


&lt;div class="ltag_gist-liquid-tag"&gt;
  
&lt;/div&gt;



&lt;p&gt;On line 6, the &lt;em&gt;ParameterBag&lt;/em&gt; class was imported. Since laravel uses &lt;a href="https://symfony.com/doc/current/create_framework/http_foundation.html" rel="noopener noreferrer"&gt;Symphony HttpFoundation component&lt;/a&gt; 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.&lt;/p&gt;

&lt;p&gt;In addition to the middleware &lt;em&gt;handle&lt;/em&gt; method, I added two other methods which are &lt;em&gt;clean&lt;/em&gt; (line 34) and _clean_Data (line 45).&lt;/p&gt;

&lt;p&gt;Let’s examine what these methods are doing.&lt;/p&gt;

&lt;h4&gt;
  
  
  Handle Method
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public function handle($request, Closure $next) {
    if ($request-&amp;gt;isJson()) {
       $this-&amp;gt;clean($request-&amp;gt;json());
    } else {
       $this-&amp;gt;clean($request-&amp;gt;request);
    }
    return $next($request);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The handle checks whether the incoming request is a json or regular request and passes the corresponding data to the clean method.&lt;/p&gt;

&lt;h4&gt;
  
  
  Clean Method
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private function clean(ParameterBag $bag) {
    $bag-&amp;gt;replace($this-&amp;gt;cleanData($bag-&amp;gt;all()));
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;There are two methods of the ParameterBag class that is quite useful to us. The first is “all” which returns an array of parameters (&lt;em&gt;in this case our form data&lt;/em&gt;) and the second method is “&lt;em&gt;replace”&lt;/em&gt; 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!!!&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h4&gt;
  
  
  CleanData Method
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;private function cleanData(array $data)                           
{   
   return collect($data)-&amp;gt;map(function ($value, $key) {  
       if ($key == 'payment\_amount') {                                        
           return preg\_replace("/([^0-9])/", '', $value);                                     
       } else {
          return $value;                               
       }                               
   })-&amp;gt;all();                           
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Our &lt;em&gt;Clean_Data method receives the array returned from the _all&lt;/em&gt; 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 &lt;em&gt;(The name of our input form field)&lt;/em&gt;, get the value using the key and remove all non-digit characters. Return the data to the ParameterBag.&lt;/p&gt;

&lt;h4&gt;
  
  
  Apply middleware
&lt;/h4&gt;

&lt;p&gt;Register this middleware in &lt;em&gt;app/Http/Kernel.php&lt;/em&gt; file as “&lt;em&gt;data.transform”&lt;/em&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...

_protected_ $routeMiddleware = [
    ...
    **'data.transform' =&amp;gt; \App\Http\Middleware\TransformData::_class_** _,_  
];
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Attach the middleware to your route or controller depending on the use-case.&lt;/p&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;In this article, we have seen how to transform our form request data with Laravel middleware, there are other use-cases for this method,&lt;a href="https://gist.github.com/samolabams/ed67bc7782ace3f6cbd80959bcdee007" rel="noopener noreferrer"&gt;Here’s the link to the github gist.&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;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 &lt;a href="https://twitter.com/samolabams" rel="noopener noreferrer"&gt;Twitter.&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Thanks for reading
&lt;/h4&gt;

</description>
      <category>middleware</category>
      <category>laravel</category>
    </item>
  </channel>
</rss>
