Function to check user birth date is 18 years or upper not always work correctly
Hi
I am beginner webdeveloper. I use in my project Laravel 5.8. I have this this code:
if ($this->calcutateAge($request->input('date')) < 18) {
return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
}
function calcutateAge($dob)
{
$dob = date("Y-m-d", strtotime($dob));
$dobObject = new DateTime($dob);
$nowObject = new DateTime();
$diff = $dobObject->diff($nowObject);
return $diff->y;
}
It's work fine. But I have problem with date ex 2045-12-12. This function is not working. With year: 2015-12-12 - it's okey.
You can do it using Carbon, which has beautiful helper functions:
$date = Carbon\Carbon::parse($request->input('date'));
if ($date->isPast() && $date->diffInYears(now()) < 18) {
return Redirect::back()->withErrors(['You are a minor. Registration is allowed for adult users']);
}
Maybe you want to break the above condition, with the check if the date is not in the past to throw a different error back, so the user does not enters dates in future.