Home > OS >  $request->validated() returns not only validated items, but everything
$request->validated() returns not only validated items, but everything

Time:07-01

I am using FormRequest to validate data, which looks like this:

public function authorize(): bool
{
    return true;
}

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules(): array
{
    return [
        'first_name' => ['required', 'string', 'max:255']
    ];
}

But if I send request like:

{
    "first_name": "Random",
    "last_name": "Guy"
}

Then $request->validated(), just like bellow example, is returning both, first and last names.

public function create(UserRequest $request)
{
    $data = $request->validated();
    return $data;
}

Any idea why is this happening? As far as I know, validated() must only return keys that exist in rules

CodePudding user response:

The problem was in nesting, I was accepting data with following structure:

$rules = [
   'userDetails' => ['required', 'array'],
   'userDetails.firstName' => ['required', 'string'],
   'userDetails.lastName' => ['required', 'string']
]

And whatever was passed in userDetails array was not being filtered, fixed by removing 'userDetails' => ['required', 'array'] from validation rules.

Looks like there's no need to use array validation

  • Related