欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

Laravel 5.2: Trim All Input using Middleware 中间件 trim 请求 处理 字段 field fields 中间件 中文英文空格 中英文空格 移除移去移掉 有大用 有大大用

Laravel 5.2: Trim All Input using Middleware

Laravel 5.2 is already good at sanitizing input data received from GET and POST data, but it doesn’t remove excessive spacing at the beginning or end of the data. This is in particular useful since some mobile devices often leave a trailing space thanks to auto-correct. Luckily, this is easy to achieve using Custom Middleware.

Create Middleware

You can using the artisan make command to help in creating the middleware file we will be using to trim all input. This can be achieved by running the command (where InputTrim is the name of the middleware):

php artisan make:middleware InputTrim

Trimming the Input

In the newly created middleware file (located at app/Http/Middleware/InputTrim.php), you just need to add one line of code above return $next($request) – see Line 18 of the below code:


<?php



namespace App\Http\Middleware;



use Closure;



class InputTrim

{

   /**

    * Handle an incoming request.

    *

    * @param  \Illuminate\Http\Request  $request

    * @param  \Closure  $next

    * @return mixed

    */

   public function handle($request, Closure $next)

   {

       // credit to @t202wes - https://gist.github.com/drakakisgeo/3bba2a2600b4c554f836#gistcomment-1970006

       $input = $request->all();



       if ($input) {

           array_walk_recursive($input, function (&$item) {

               $item = trim($item);

               $item = mb_ereg_replace('(^( | )+|( | )+$)', '', $item);   #这一行是我自己加上去的,去除中英文空格

               $item = ($item == "") ? null : $item;


               

           });



           $request->merge($input);

       }



       return $next($request);

   }

}
view rawInputTrim.php hosted with ❤ by GitHub

Updating the Laravel Kernel

Once you have updated the middleware, you need to tell Laravel to run the middleware on every request (or for a particular group). To do this, you need to update the app/Http/Kernel.php file.

To run the Middleware on all HTTP requests, add line 11 from the below code  to the end of the $middleware array:


<?php



namespace App\Http;



use Illuminate\Foundation\Http\Kernel as HttpKernel;



class Kernel extends HttpKernel

{

   protected $middleware = [

       // ..

       \App\Http\Middleware\InputTrim::class,

   ];



   protected $middlewareGroups = [

       // ...

   ];



   protected $routeMiddleware = [

       // ...

   ];

}
view rawKernel.php hosted with ❤ by GitHub

Your Kernel.php should look like the above example. In our version, we have removed other middleware and group settings.


来自  https://www.webniraj.com/2017/02/21/laravel-5-2-trim-all-input-using-middleware/

普通分类: