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

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

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()

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...)


答案 1

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

例:

public function store(Request $request)
{
    $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

    $validatedData = $request->validated();

}

替代解决方案:

$request->validate([rules...])如果验证通过,则返回唯一已验证的数据。

例:

public function store(Request $request)
{
   
    $validatedData = $request->validate([
        'title' => 'required|unique:posts|max:255',
        'body' => 'required',
    ]);

}

答案 2

还行。。。在我花了时间输入这个问题之后,我想我会检查一下laravel“API”文档: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())]);
}

推荐