ItSolutionStuff.com

Laravel Calculate Age from Date of Birth Example

By Hardik Savani • April 16, 2024
PHP Laravel

In this small tutorial, i will show you how to calculate age from date using carbon in laravel 5, laravel 6, laravel 7, laravel 8, laravel 9, laravel 10 and laravel 11 application.

If you work on big web application then you might be sometime require to age calculate from date of birth. Like your birth date is around 02/07/1994 and today date like 10/9/2018 then it should be return 24 years old you are.

So, you can simply age calculation by using laravel carbon. So just see example:

Example 1:

You can see the following controller file code:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use Carbon\Carbon;

class DemoController extends Controller

{

/**

* Write code on Method

*

* @return response()

*/

public function index(Request $request)

{

$dateOfBirth = '1994-07-02';

$years = Carbon::parse($dateOfBirth)->age;

dd($years);

}

}

Example 2:

You need to add age() function in User model as like the below:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;

use Illuminate\Foundation\Auth\User as Authenticatable;

use Illuminate\Notifications\Notifiable;

use Laravel\Sanctum\HasApiTokens;

use Carbon\Carbon;

class User extends Authenticatable

{

....

/**

* Accessor for Age.

*/

public function age()

{

return Carbon::parse($this->attributes['birthdate'])->age;

}

}

You can use with $user object as like the below:

<p>{{ $user->age() }} years</p>

I hope it can help you...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

How to Get All Models in Laravel?

Read Now →

How to Create Model in Laravel using Command?

Read Now →

Laravel 9 Enum Model Attribute Casting Example

Read Now →

Laravel Eloquent whereRelation() Condition Example

Read Now →

Laravel Eloquent Model Custom Function Example

Read Now →

How to Create Custom Model Events in Laravel?

Read Now →

Laravel Eloquent Group By Example

Read Now →

Multiple orWhere Condition in Laravel Eloquent

Read Now →

Laravel One to Many Eloquent Relationship Tutorial

Read Now →

Laravel Improve Speed Performance using Model Caching Tutorial

Read Now →

How to disable model timestamps in Laravel?

Read Now →

How to Get Table Name from Model in Laravel?

Read Now →

How to Get Query Log in Laravel Eloquent?

Read Now →