加入 Day, Month , Year 的列来计算年龄

Join columns of Day, Month , Year to calculate age

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

    // ....
}

我只需要查看年龄。谢谢,我正在使用 blade.php 顺便说一句

您可以使用 "Accessor" 来获取年龄。

  • 定义一个 getAgeAttribute 方法来计算年龄 Patients 型号
  • 将方法附加到模型
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;
    }
}

然后像这样使用它

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