How can I check the age of a user upon registration? I want to set the minimum age to be 13 years old. I ask for the user's date of birth and when I validate the other credentials, I want to check that they are in fact 13+.
An excerpt from my User model looks like this:
$rules = [
'name' => 'required|alpha|min:1',
'email' => 'required|email|unique:users',
'dob' => 'required|date'
];
How can I check that the date entered is 13 years ago or more?
I have seen that I can use the before:yyy-mm-dd
rule from the Laravel Docs, like so:
$rules = [
'name' => 'required|alpha|min:1',
'email' => 'required|email|unique:users',
'dob' => 'required|date|before:2001-04-15'
];
You can use Carbon which comes with laravel
$dt = new Carbon\Carbon();
$before = $dt->subYears(13)->format('Y-m-d');
$rules = [
...
'dob' => 'required|date|before:' . $before
];
A simple way to check that the date is greater(older) than N years is to set the before
rule to minus N years.
$rules = [
'dob' => 'required|date|before:-13 years',
]
RMcLeod answer is OK, but I'd suggest you extracting this as a custom rule:
Validator::extend('olderThan', function($attribute, $value, $parameters)
{
$minAge = ( ! empty($parameters)) ? (int) $parameters[0] : 13;
return (new DateTime)->diff(new DateTime($value))->y >= $minAge;
// or the same using Carbon:
// return Carbon\Carbon::now()->diff(new Carbon\Carbon($value))->y >= $minAge;
});
This way you can use the rule for any age you like:
$rules = ['dob' => 'olderThan']; // checks for 13 years as a default age
$rules = ['dob' => 'olderThan:15']; // checks for 15 years etc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With