如何仅从laravel FormRequest中获取经过验证的数据? [英] How do I get ONLY the validated data from a laravel FormRequest?
本文介绍了如何仅从laravel FormRequest中获取经过验证的数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
让我们说我有以下自定义请求:
Lets say I have the following Custom Request:
class PlanRequest extends FormRequest
{
// ...
public function rules()
{
return
[
'name' => 'required|string|min:3|max:191',
'monthly_fee' => 'required|numeric|min:0',
'transaction_fee' => 'required|numeric|min:0',
'processing_fee' => 'required|numeric|min:0|max:100',
'annual_fee' => 'required|numeric|min:0',
'setup_fee' => 'required|numeric|min:0',
'organization_id' => 'exists:organizations,id',
];
}
}
当我从控制器访问它时,如果执行$request->all()
,它将为我提供 ALL 数据,包括不需要传递的多余垃圾数据.
When I access it from the controller, if I do $request->all()
, it gives me ALL the data, including extra garbage data that isn't meant to be passed.
public function store(PlanRequest $request)
{
dd($request->all());
// This returns
[
'name' => 'value',
'monthly_fee' => '1.23',
'transaction_fee' => '1.23',
'processing_fee' => '1.23',
'annual_fee' => '1.23',
'setup_fee' => '1.23',
'organization_id' => null,
'foo' => 'bar', // This is not supposed to show up
];
}
如何仅获得经过验证的数据,而无需手动执行$request->only('name','monthly_fee', etc...)
?
How do I get ONLY the validated data without manually doing $request->only('name','monthly_fee', etc...)
?
推荐答案
$request->validated()
将仅返回经过验证的数据.
示例:
public function store(Request $request)
{
$request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
$validatedData = $request->validated();
}
替代解决方案:
如果验证通过, $request->validate([rules...])
将返回唯一的验证数据.
Alternate Solution:
$request->validate([rules...])
returns the only validated data if the validation passes.
示例:
public function store(Request $request)
{
$validatedData = $request->validate([
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
}
这篇关于如何仅从laravel FormRequest中获取经过验证的数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文