我有一个 TrimInput 中间件注册为我的路由的中间件,以便在请求到达控制器之前修剪所有用户输入。在中间件中,修剪似乎有效,但是当我将请求转储到操作中时,请求似乎未修改,就像以前没有中间件一样。
这里有什么问题?问题出在 ClientRequest 上,但为什么呢?
// 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
}]);
编辑: 事实证明,上面的代码可以正常工作,但不幸的是我的
ClientRequest
忽略了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'
];
}
}
您应该首先在您的 app/Http/Kernel.php 文件中为中间件分配一个快捷键。像下面这样
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
'trim' => 'App\Http\Middleware\TrimInput ',
];
为了让中间件修改
FormRequest
上的请求输入,您需要使用 all()
上的 /app/Http/Requests/Request.php
方法覆盖它,因为它是在中间件执行之前加载的。我相信 Laravel 5.4 中已经修复了这个问题。
这对我有用。在 Request.php 中添加此方法,它将应用在中间件中完成的更改。
public function all()
{
$this->merge( $this->request->all() );
return parent::all();
}
使用框架的 Illuminate\Foundation\Http/Middleware\TrimStrings.php 中间件并将其添加到您的
web
中间件组