Tags: PHP
Sometimes when validating forms, you need to have all (or almost all) fields be required. Instead of typing them all, I came up with a fairly elegant way of only excluding non-required fields from validation.
First, let's get all the columns from the model. You should have your hidden columns at the top of the model, which should include "id", "created_at", etc. You can also specify other system columns, which you don't want to require.
/**
* Get all required columns from the table
*
* @param $exceptions, array
* @
*/
public function getRequiredColumns($exceptions = [])
{
// Prepare all columns to ignore
$systemColumns = ['id', 'submitted_by', 'created_at', 'updated_at'];
$ignore = array_merge($systemColumns, $exceptions);
// Get all columns
$columns = Schema::getColumnListing($this->table);
// Remove ignored columns from all
foreach ($ignore as $key => $val) {
$columnId = array_search($val, $columns);
if ($columnId !== false) {
unset($columns[$columnId]);
}
}
return $columns;
}
Great, now, let's validate. Notice that I added another array of checkboxes. I think it's more elegant than the standard way of passing the associative array with "accepted" or "required" on all fields.
/**
* Validate submitted fields
* @param $data, array
* @return JSON or null
*/
public function validate($data)
{
// Validate that checkboxes are checked
$checkboxes = ['checkbox1', 'checkbox2', 'checkbox3'];
$checked = array_fill_keys($checkboxes, 'accepted');
// Get required columns
$ignore = ['address2'];
$except = array_merge($checkboxes, $ignore);
$columns = $this->getRequiredColumns($except);
$required = array_fill_keys($columns, 'required');
// Validate
$rules = array_merge($checked, $required);
$validator = Validator::make($data, $rules);
return $validator->errors();
}
©2023, kirillsimin.com