Skip to content

Instantly share code, notes, and snippets.

@dkesberg
Created February 23, 2022 10:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkesberg/80cb5dd7cf3a2b9b435d6ffd93970b23 to your computer and use it in GitHub Desktop.
Save dkesberg/80cb5dd7cf3a2b9b435d6ffd93970b23 to your computer and use it in GitHub Desktop.
Laravel request validation: Missing array values after POST request from input[type="checkbox"] fields

Problem:

Browsers don't submit any value for checkboxes that are unchecked.

If you have optional checkboxes the request will validate using $data = $request->validate($rules) but any checkbox field is missing from the returned $data array. This means you still have to check if the index exists in the $data array as trying to access the field will throw an exception.

Solution

Set a default value for each optional checkbox fields before validation.

function post(Request $request)
{
$rules = [
'items' => 'nullable|array'
];
// set default value for optional array fields
$request->merge(['items' => $request->input('items', [])]);
// validate as usual
$data = $request->validate($rules);
// no need to check for index
if ($data['items']) {
// do stuff with array entries
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment