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

◇◆丶佛笑我妖孽 提交于 2019-12-04 09:39:57

问题


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


回答1:


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 getAgeAttribute()
{
    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>



回答2:


To show directly in your view:

\Carbon\Carbon::parse($user->birth)->diff(\Carbon\Carbon::now())->format('%y years, %m months and %d days');



回答3:


Calculating the age in Laravel is best done using the build in Carbon. Dates returned in Laravel are already in a Carbon format.

This logic should go in the model as a default getter for your model.

public function getAge(){
    $this->birthdate->diff(Carbon::now())
         ->format('%y years, %m months and %d days');
}

This will result in "23 years, 6 months and 26 days"

Checkout the http://carbon.nesbot.com/docs/ docs for all the fun stuff you can do with it.

Assuming you are using models in your view and since you should make a getAge() function in that model.

You can call your model in the view as $user->getAge()




回答4:


Thanks for all you suggestion.

That was easy and awesome with carbon.

I added this code in Model:

public function age() {
return $this->dob->diffInYears(\Carbon::now());
 }



回答5:


I also manage to get change the date format 'Y-m-d' from database to passing date in this 'd-m-Y' in view .

I place this code in model

public function getDOB(){ 
return $this->dob->format('d-m-Y'); 
 }


来源:https://stackoverflow.com/questions/35524482/calculate-age-from-date-stored-in-database-in-y-m-d-using-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!