Calculate age from date of birth in Laravel

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.

Answers 2
  • 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";
    
    -1
    //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;
    
    0
    //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