Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Age from date stored in database in Y-m-d using Laravel 5.2

Tags:

Hi User's add their DOB through the Form that store in database,

I would like calculate age from stored date in the database which is in this format Y-m-d,

My Question is :

  • How to calculate Age?

  • Where to put the logic , In Controller or Model?

  • How to pass the stored Date in view in this format 'm-d-Y'

  • How to pass the result of logic which is age in view.

  • I am using something as below in my model is this Right?

This is controller:

public function index()   {   
    $profile   = User::find($this->userid())->profiledetailsHasOne;  //This has Dob field                   
    return view('profile.index',['profile' => $profile ]); 
}

This is my Model:

public function getAge(){
    $this->birthdate->diff($this->attributes['dob'])
    ->format('%y years, %m months and %d days');
}

This is my View:

<tr>
    <th>Age</th>
    <td>{{$profile->getAge()}}</td>
</tr>

Is this Right? I am getting error as below

Call to a member function diff() on null

like image 782
sanainfotech Avatar asked Feb 20 '16 14:02

sanainfotech


People also ask

How do I get age from DateTime?

int age = (int) ((DateTime. Now - bday). TotalDays/365.242199);

How do I calculate age in mysql?

Here is the query to calculate the age from D.O.B. The query is as follows. mysql> select StudentName,StudentDOB,year(curdate())-year(StudentDOB) as StudentAge from AgeDemo; The following is the output displaying age.


2 Answers

Dates can be instances of Carbon, which provides an assortment of helpful methods.

In your model, import the Carbon class:

use Carbon\Carbon;

And define an accessor:

/**
 * Accessor for Age.
 */
public function age()
{
    return Carbon::parse($this->attributes['birthdate'])->age;
}

You can then call age as if it was a regular attribute. For example in a blade view:

<p>{{ $user->age() }} years</p>
like image 185
Florent B. Avatar answered Sep 19 '22 16:09

Florent B.


To show directly in your view:

\Carbon\Carbon::parse($user->birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');
like image 41
Gabriel Glauber Avatar answered Sep 17 '22 16:09

Gabriel Glauber