我有一个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'
];
}
}
答案 0 :(得分:0)
您应首先在 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 ',
];
答案 1 :(得分:0)
为了使中间件能够修改FormRequest
上的请求输入,您需要使用all()
上的/app/Http/Requests/Request.php
方法覆盖它,因为它是在中间件之前加载的被执行。我认为这在Laravel 5.4中得到了修复。
这对我有用。在Request.php中添加此方法,它将应用在中间件中完成的更改。
public function all()
{
$this->merge( $this->request->all() );
return parent::all();
}
答案 2 :(得分:0)
使用框架的Illuminate \ Foundation \ Http / Middleware \ TrimStrings.php
中间件并将其添加到您的web
中间件组