How do I get ONLY the validated data from a laravel FormRequest?

╄→гoц情女王★ 提交于 2019-12-22 08:34:06

问题


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',
        ];
    }
}

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
    ];
}

How do I get ONLY the validated data without manually doing $request->only('name','monthly_fee', etc...)?


回答1:


$request->validated() will return only the validated data.

In your store method:

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



回答2:


OK... After I spent the time to type this question out, I figured I'd check the laravel "API" documentation: https://laravel.com/api/5.5/Illuminate/Foundation/Http/FormRequest.html

Looks like I can use $request->validated(). Wish they would say this in the Validation documentation. It makes my controller actions look pretty slick:

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


来源:https://stackoverflow.com/questions/47936337/how-do-i-get-only-the-validated-data-from-a-laravel-formrequest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!