gpt4 book ai didi

laravel - 在中间件中修改请求?

转载 作者:行者123 更新时间:2023-12-03 17:43:21 25 4
gpt4 key购买 nike

我有一个 TrimInput 中间件注册为我的路由的中间件,用于在请求到达 Controller 之前修剪所有用户输入。在中间件中,修剪似乎有效,但是当我在操作中转储请求时,请求似乎未修改,就像之前没有中间件一样。

这里有什么问题?问题是 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 ',
];

关于laravel - 在中间件中修改请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30546461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com