如何仅从lavalvel FormRequest获取经过验证的数据?

时间:2017-12-22 05:36:25

标签: php laravel validation request-validation

假设我有以下自定义请求:

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 数据,包括不会传递的额外垃圾数据。< / p>

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...)的情况下验证数据?

2 个答案:

答案 0 :(得分:7)

$request->validated()将仅返回经过验证的数据。

在您的商店方法中:

public function store(PlanRequest $request)
{
    $data = $request->validated();
}

答案 1 :(得分:5)

好的......在我花时间输入这个问题之后,我想我会检查laravel&#34; API&#34;文档:https://laravel.com/api/5.5/Illuminate/Foundation/Http/FormRequest.html

看起来我可以使用$request->validated()。希望他们在验证文档中说出这一点。它使我的控制器动作看起来很漂亮:

public function store(PlanRequest $request)
{
    return response()->json(['plan' => Plan::create($request->validated())]);
}