phplaravelvalidationlaravel-8laravel-formrequest

Why we retrieve the validated input data when using form request?


I'm using Laravel 8, and in the Laravel document, I see this line of code for retrieving the validated input data then using form requests.

// Retrieve the validated input data...
$validated = $request->validated();

But if I clear this line, everything is fine! So, What is the reason for this retrieval?


Solution

  • The ->validated() method returns information from your request that actually underwent validation. Let's use a quick scenario:

    dd($request->input());
    // ['name' => 'John', 'middle_name' => 'Smith', 'last_name' => 'Doe']
    

    If you have the following rules:

    $rules = ['name' => 'required', 'last_name' => 'required'];
    

    Then, after running validation, calling ->validated() will return the following:

    dd($request->validated());
    // ['first_name' => 'John', 'last_name' => 'Doe']
    

    Notice how middle_name is missing? It was not included in the validation rules, and as such is stripped out.

    You can read the full documentation here:

    https://laravel.com/docs/8.x/validation#working-with-validated-input

    Note: If you're validating everything in your $request, i.e. first_name, middle_name and last_name, then you can use $request->validated(), $request->input() or $request->all(); they will all be the same.