Laravel如何修改request的值
如何在request验证之前修改request里面的值?我们可以这样:
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class DemoRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
public function prepareForValidation()
{
$this->replace([
'from' => '123',
]);
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
//
];
}
}
在 Request 文件中定义了 prepareForValidation
函数,并调用 replace
对request里面的值进行覆盖。这里有一点需要注意,我们先来看下 replace()
的代码:
public function replace(array $input)
{
$this->getInputSource()->replace($input);
return $this;
}
protected function getInputSource()
{
if ($this->isJson()) {
return $this->json();
}
return in_array($this->getRealMethod(), ['GET', 'HEAD']) ? $this->query : $this->request;
}
注意,如果你是GET或者HEAD访问那么你只能修改 query 参数,如果是非 GET 和 HEAD,那么只能修改 body里面的内容了。
本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。
评论已关闭