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

sanainfotech's avatar

Calculate age from Date stored for all profiles in MySql Column

Hi, I have stored Date of birth for all profiles in my MySQL, Now on my index page, I would like to show all profile with their age.

  public function index(User $user){
    $users = $user->join('personaldetails', 'users.id', '=', 'personaldetails.user_id')-           
  >get();
    
    
    return view('index',compact('users'));
}

The above code joins 2 table which is 'users' and 'personaldeatails' , I am able to echo all feilds but What is the best way to echo age of all theses profiles

0 likes
7 replies
martinbean's avatar

@sanainfotech If you cast your date of birth field to a date, you can use Carbon to get the age:

@foreach ($users as $user)
    {{ $user->date_of_birth->age }}
@endforeach

You cast the column to a date in your model:

class User extends Authenticatable
{
    protected $casts = [
        'date_of_birth' => 'date',
    ];
}
sanainfotech's avatar

@martinbean Thanks for quick answer, It seems to be perfect solution, I followed all the mentioned steps. But I am getting error in viewing the page as below,

ErrorException in  line 33:
Trying to get property of non-object (View: 
martinbean's avatar

@sanainfotech Have you used the name of whatever column you’re storing the date of birth in, rather than copy-and-pasting my answer?

sanainfotech's avatar

Hi @martinbean, I have changed, as my column in database table is dob, So ,

@foreach ($users as $user)
{{ $user->dob->age }}
@endforeach 

Model

class User extends Authenticatable
{
protected $casts = [
    'dob' => 'date',
];
}

I am able to echo dob column,

@foreach ($users as $user)
{{ $user->dob }}
@endforeach 

Result Age: 1981-05- 04

But when I add age this error comes

 @foreach ($users as $user)
{{ $user->dob->age }}
@endforeach 

Error

ErrorException in  line 33:
Trying to get property of non-object (View:

Please or to participate in this conversation.