Calculate age from date of birth in Laravel

Created at 20-May-2021 , By samar

Calculate age from date of birth in Laravel

Hello everyone, in this post we will look at how to solve "Calculate age from date of birth in Laravel" in programming.

You can easily calculate age from a given date of birth in Laravel. Laravel provides different methods on carbon class to calculate the difference between two dates, create date format and change the date format. You don’t have to create any custom function to get the age from the date of birth in Laravel.
  • Calculate age in years from date for birth in laravel using Carbon

    //Date format Y-m-d 
    $dateOfBirth = '1992-4-4';
    $age = \Carbon\Carbon::parse($dateOfBirth)->age;
    echo "You are ". $age . " years old";
    
    //Output
    You are 29 years old

    You can use the parse() method with age on the \Carbon\Carbon class to get the age on the basis of date of birth.

    You can use this code snippet in your controller methods and you can also use it in your view file by passing the value to it.

  • Calculate age in Laravel with years, months and days using Carbon

    //Date format Y-m-d 
    $dateOfBirth = '1992-4-4';
    
    $age = \Carbon\Carbon::parse($dateOfBirth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');
    echo $age;
    
    //Output
    29 years, 1 months and 15 days

    You can also calculate age from a given date in Laravel with years, months, and days using Carbon class. You can use this code snippet in the controller and in your view files.

Back to code snippet queries related laravel

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.