Skip to content

Instantly share code, notes, and snippets.

@joshuadegier
Created June 13, 2016 07:55
Show Gist options
  • Save joshuadegier/843c2b9ef366a5b4dd49f7503724ed4c to your computer and use it in GitHub Desktop.
Save joshuadegier/843c2b9ef366a5b4dd49f7503724ed4c to your computer and use it in GitHub Desktop.
Validation rule for Laravel to check existence in database or pass validation if value is 0 or null
/**
* Validate exists_or_null
* This rule validates exactly like the default 'exists' rule, except it passes
* when the value is equal to 0 or null. The function should be added to the
* boot method of the AppServiceProvider. When there's another value than
* 0 or null, the value will be validated against the default exists
* rule.
*/
Validator::extend(
'exists_or_null',
function ($attribute, $value, $parameters)
{
if($value == 0 || is_null($value)) {
return true;
} else {
$validator = Validator::make([$attribute => $value], [
$attribute => 'exists:' . implode(",", $parameters)
]);
return !$validator->fails();
}
}
);
/**
* You can validate select lists like these
*/
$category_list = CompanyCategory::withParent(0)->lists('name', 'id');
$category_list->prepend('Please select a parent category (optional)'); // this results in <option value="0">Please select a parent category (optional)</option>
/**
* Now if we would validate the field using 'exists_or_null' instead of 'exists'
* it would pass validation because 0 is a valid option aswel. If another
* value was selected, that value will be validated against 'exists'
* using the exact same parameters.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment