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

JonTroncoso picture JonTroncoso · Dec 22, 2017 · Viewed 19.8k times · Source

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

Answer

Sapnesh Naik picture Sapnesh Naik · Dec 22, 2017

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

Example:

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

    $validatedData = $request->validated();

}

Alternate Solution:

$request->validate([rules...]) returns the only validated data if the validation passes.

Example:

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

}