Reputation: 913
I have a TrimInput middleware registrated as a middleware for my routes to trim all user input before the request hits the controller. Within the middleware the trimming seems working, but when I dump the request in the action the request seems unmodified like there was no middleware before.
What's the problem here? The problem is the 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 above code is working, but unfortunately my ClientRequest
ignores the 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'
];
}
}
Upvotes: 5
Views: 5587
Reputation: 1944
use the framework's Illuminate\Foundation\Http/Middleware\TrimStrings.php
middleware and add it to your web
middleware group
Upvotes: 0
Reputation: 534
In order for the middleware to and modify the request input on FormRequest
, you need to overwrite it using the all()
method on /app/Http/Requests/Request.php
because it's loaded before the middleware is executed. This was fixed in Laravel 5.4 I believe.
Here's what worked for me. Add this method in Request.php and it will apply the changes done in your middleware.
public function all()
{
$this->merge( $this->request->all() );
return parent::all();
}
Upvotes: 0
Reputation: 1787
You should first assign the middleware a short-hand key in your app/Http/Kernel.php file. like below
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'trim' => 'App\Http\Middleware\TrimInput ',
];
Upvotes: 1