Take a look at this sample validation code, taken straight from the Laravel documentation:
use Illuminate\Support\Facades\Validator;
$input = [
'user' => [
'name' => 'Taylor Otwell',
'username' => 'taylorotwell',
'admin' => true,
],
];
Validator::make($input, [
'user' => 'array:name,username',
]);
As expected, this code fails validation because the unexpected admin
key was passed in as part of the user
array. This key was not explicitly allowed, so it gets rejected.
This is great! But the one thing that initially confused me was the error message which was returned:
The user field must be an array.
This sounds like a data type issue, as if I had passed in a string or number instead of an array.
Instead, I was expecting something more along the lines of:
The user field must only contain entries for: name, username.
That error is more clear, and aligns with the helpful error message returned by the required_array_keys
rule.
I understand why the error message is the way it is. It's the same validatesArray
function getting called in both cases.
To be clear: I definitely think the rule is important to specify. It provides critical protection against unexpected data being passed into your application.
I'm only sharing in case it trips you up, like it did for me.
Here to help,
Joel
P.S. If only there was a whole book full of Laravel validation wisdom like this.