Change request in middleware?

I have TrimInput middleware registered as middleware for my routes to trim all user input before the request hits the controller. Inside the middle layer, cropping seems to work, but when I drop the request in action, the request seems unmodified, as there was no middleware before.

What is the problem? The problem is ClientRequest, but why?

// TrimInput.php <?php namespace App\Http\Middleware; use Closure; class TrimInput { /** * Handle an incoming request. * * @param \Illuminate\Http\Request $request * @param \Closure $next * * @return mixed */ public function handle($request, Closure $next) { $request->replace($this->trimArrayRecursive($request->all())); // When I dump $request right here, all seems fine (the input is trimmed) return $next($request); } protected function trimArrayRecursive($input) { if (!is_array($input)) { return trim($input); } return array_map([$this, 'trimArrayRecursive'], $input); } } // Somwhere in my routes.php Route::post('/test', ['middleware' => 'trim', 'uses' => function(\App\Http\Requests\ClientRequest $request) { dd($request->all()); // Unfortunately dumps the unfiltered (untrimmed) input }]); 

EDIT: It turned out that the code above works, but unfortunately my ClientRequest ignores TrimInputMiddleware .

 // ClientRequest.php <?php namespace App\Http\Requests; class ClientRequest extends Request { /** * Determine if the user is authorized to make this request. * * @return bool */ public function authorize() { return true; } /** * Get the validation rules that apply to the request. * * @return array */ public function rules() { $idToIgnore = $this->input('id'); return [ 'name' => 'required|max:255|unique:clients,name,' . $idToIgnore, 'street' => 'required|max:255', 'postal_code' => 'required|digits:5', 'city' => 'required|max:255', 'contact_person' => 'required|max:255' ]; } } 
+5
source share
3 answers

You must first assign the middleware to the short key in the application file /Http/Kernel.php . as below

 protected $routeMiddleware = [ 'auth' => 'App\Http\Middleware\Authenticate', 'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth', 'guest' => 'App\Http\Middleware\RedirectIfAuthenticated', 'trim' => 'App\Http\Middleware\TrimInput ', ]; 
0
source

In order for the middleware to change the input request of the request to FormRequest , you need to overwrite it with the all() method on /app/Http/Requests/Request.php , because it is loaded before the middleware /app/Http/Requests/Request.php . This was fixed in Laravel 5.4. I suppose.

Here is what worked for me. Add this method to Request.php and apply the changes made to your middleware.

 public function all() { $this->merge( $this->request->all() ); return parent::all(); } 
0
source

use the Illuminate \ Foundation \ Http / Middleware \ TrimStrings.php middleware frame and add it to your middleware web group

0
source

All Articles