Home > Back-end >  Join columns of Day, Month , Year to calculate age
Join columns of Day, Month , Year to calculate age

Time:05-07

enter image description here

public function patients_view($id)
{
    $patient =  Patients::where('id', '=', $id)->first();

    // ....
}

I just need to view the age. Thanks , im using blade.php btw

CodePudding user response:

You can use an "Accessor" to get the age.

  • Define a getAgeAttribute method that calculate the age in the Patients model
  • Append the method to the model
class Patients extends Model
{
    protected $appends = ['age'];

    /**
     * Get the patients's age.
     *
     * @param  string  $value
     * @return string
     */
    public function getAgeAttribute($value)
    {
        $age = (time() - strtotime($this->dobDay.' '.$this->dobMonth.' '. $this->dobYear)) / (60 * 60 * 24 * 365);
        $age = floor($age);

        return $age;
    }
}

And use it like so

public function patients_view($id)
{
    $patient =  Patients::where('id', '=', $id)->first();
    dd($patient->age);
    // ....
}
  • Related