How to Calculate Age from Date of Birth (dob) in Laravel ?

In this simple tutorial, You will learn to calculate age using carbon in laravel.

First of all, you need some software to get started with laravel project : 

  • Xampp
  • Composer
  • Cmd

First Step

  1. Goto C:\Xampp\htdocs
  2. Shift + Right Click to Open Command prompt here
  3. In Command prompt type (composer require nesbot/carbon) and press ↵ Enter.
  4. Carbon will immediately begin to install.

2nd Step

use Illuminate\Support\Carbon; //Include the below line in the header section above the class

Example 1 :

public function index()

{

$dob= ‘1949-12-20’; // Assuming birth date is around 1949-12-20 

$DateOfBirth = Input::get(‘dob’); // get the request date

$age = Carbon::parse($dateOfBirth)->age; // calculate the age

dd($age); // print the final result

}

Result = 50 // Years

Example 2 :

public function index()

{

$dob= ‘1999-12-20’; // Assuming birth date is around 1999-12-20

$DateOfBirth = Input::get(‘dob’); // get the request date

$age = \Carbon\Carbon::parse($dateOfBirth)->diff(\Carbon\Carbon::now())->format(‘%y years, %m months and %d days’); // calculate the age

dd($age); // print the final result

}

Result = 22 years, 0 months and 5 days”

Final Words

The steps provided by me in this tutorial is easy to perform by any person who is having a basic knowledge of computer. I’m happy to help you to fix that problem.

Posted in LaravelTags:

Write a comment