PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, March 7, 2022

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

 March 07, 2022     database, date, laravel-5.2, php     No comments   

Issue

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


Solution

To show directly in your view:

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


Answered By - Gabriel Glauber
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing