Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

trifek's avatar

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.

How can I repair it?

0 likes
6 replies
Nakov's avatar

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.

2 likes
trifek's avatar

It's not help. When I have 2045-12-12 - yours function not working :(

automica's avatar

@trifek @nakov commented that you'd also need to add something like

if (!$date->isPast())  {
    return Redirect::back()->withErrors(['You have set a date in the future. Registration is allowed for adult users']);
}
Nakov's avatar
Nakov
Best Answer
Level 73

Yeah @trifek read the comments :)

Like @automica solution, but even more readable this way:

if ($date->isFuture())  {
    return Redirect::back()->withErrors(['You have set a date in the future. Registration is allowed for adult users']);
}
automica's avatar

@nakov adding the ! saved me from checking for the right method name :P

Please or to participate in this conversation.