人気のPHP WEBアプリケーションフレームワークLaravelのTipsを記録していきます

Laravel の モデル で 生年月日から 和暦(昭和45年6月27日)を返すアクセサーを定義する

    /**
     * アクセサー : 「->patient_birth_date_wareki」 で 値「昭和45年6月27日」のフォーマットで誕生日を返す
     */
    public function getPatientBirthDateWarekiAttribute()
    {
        if ( $this->attributes['patient_birth_date'] != null ){
            $c = new \Carbon\Carbon($this->attributes['patient_birth_date']);
            setlocale(LC_TIME, 'ja_JP.utf8');
            $format = '%EC%Ey年%-m月%-d日';
            return $c->formatLocalized($format);
        } else {
            return 'ERROR: getPatientBirthDateWarekiNengoAttribute()';
        }
    }


    /**
     * アクセサー : 「->patient_birth_date_wareki_nengo」 で 値「昭和」を返す
     */
    public function getPatientBirthDateWarekiNengoAttribute()
    {
        if ( $this->attributes['patient_birth_date'] != null ){
            $c = new \Carbon\Carbon($this->attributes['patient_birth_date']);
            setlocale(LC_TIME, 'ja_JP.utf8');
            $format = '%EC';
            return $c->formatLocalized($format);
        } else {
            return 'ERROR: getPatientBirthDateWarekiNengoAttribute()';
        }
    }


    /**
     * アクセサー : 「->patient_birth_date_wareki_nengo」 で 年号以降の和暦の誕生日を返す
     */
    public function getPatientBirthDateWarekiNengappiAttribute()
    {
        if ( $this->attributes['patient_birth_date'] != null ){
            $c = new \Carbon\Carbon($this->attributes['patient_birth_date']);
            setlocale(LC_TIME, 'ja_JP.utf8');
            $format = '%Ey年%-m月%-d日';
            return $c->formatLocalized($format);
        } else {
            return 'ERROR: getPatientBirthDateWarekiNengoAttribute()';
        }
    }

・使い方

dump($model->patient_birth_date); // DB に入っている誕生日
dump($model->patient_birth_date_wareki);
dump($model->patient_birth_date_wareki_nengo);
dd($model->patient_birth_date_wareki_nengappi);

・結果

Carbon @1548926428 {#558 ▼
  date: 2019-01-31 18:20:28.0 Asia/Tokyo (+09:00)
}
"平成31年1月31日"
"平成"
"31年1月31日"
No.1433
01/31 18:22

edit