get Attributeとは、Eloquentモデルのアクセサメソッドで、モデルのデータを取得する際に、変換データを作成するためのメソッド。
方法
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
変換したいデータがあるモデルにfunction get Attribute()で書く
↓
そのデータをbladeで使用するのであれば必要ないが、vueで使用する場合は protected $appends = []の中に指定必要。
ーーーーーーーーーーーーーーーーーーーーーーーーーーーーー
使用事例
・半角カナから全角カナへ変換 & null対策
//普通はこの書き方でOKだがDBにデータが無い時や、新規フォームの場合エラーがでてしまうから、
function getNameKanaHalfToFullAttribute()
{
}
// DBが空の場合nullを返してエラーにならないようにしておく
function getNameKanaHalfToFullAttribute()
{
}
return null;
}
・last_name(名字)カラムとfirst_name(名前)カラムを一つにしてvueに表示したい時
protected $appends = [
'full_name',
'full_name',
];
{
return $this->last_name.' '.$this->first_name;
}
・last_name(名字)カラムとfirst_name(名前)カラムを全角で表示したい時
protected $appends = [
'representative_full_name_half_to_full',
];
function getRepresentativeFullNamehalfToFullAttribute() {
return $convertedLastName.' '.$convertedFirstName;
}
・半角文字を全角に変換(↓は名前に半角があった場合)
protected $appends = [
'full_name_half_to_full',
'full_name_half_to_full',
];
function getFullNamehalfToFullAttribute()
{
// mb_convert_kanaを使用 'A(英数字)S(スペース)K(カタカナ)V(濁点付きを1文字にする)'
// mb_convert_kanaを使用 'A(英数字)S(スペース)K(カタカナ)V(濁点付きを1文字にする)'
return $convertedLastName.' '.$convertedFirstName;
}
※全角を半角に。等詳しいことはここ
・郵便番号が【1040032】と登録されている状態から3桁と4桁に分けたい場合
protected $appends = [
'zip_code_parent',
'zip_code_child',
];
function getZipCodeParentAttribute()
{
return substr($this->zip_code, 0, 3); // 先頭の3桁を取得
}
function getZipCodeChildAttribute()
{
return substr($this->zip_code, -4); // 末尾の4桁を取得
}
・住所が都道府県、市町村などバラバラで登録されてるものを一行で表示したい場合
protected $appends = [
'full_address_without_zip_code',
'full_address_without_zip_code',
];
function getFullAddressWithoutZipCodeAttribute() {
return
$this->prefecture.
$this->address1.
$this->address2.
$this->address3;
}
・電話番号【090-1234-5678】と登録されている状態からハイフンのとこで3部に分けたい場合
protected $appends = [
'tel_1',
'tel_2',
'tel_3',
];
function getTel1Attribute()
{
$tell_array = explode('-', $this->tel);
return $tell_array[0] ?? ''; // 090の部分
}
function getTel2Attribute()
{
$tell_array = explode('-', $this->tel);
return $tell_array[1] ?? ''; // 1234の部分
}
function getTel3Attribute()
{
$tell_array = explode('-', $this->tel);
return $tell_array[2] ?? ''; // 5678の部分
}
・データの文字の一部を抽出
novaの場合、fieldで->displayUsingで抽出することも可能(リンク)
protected $appends = [
'age',
];
public function getAgeAttribute()
{
// 「1952/02/17 生」というデータを「1952/02/17」「生」に分割
$birthParts = explode(' ',$this->representative->birthdate);
// $dateParts の値は次のようになる
// array(2) {
// [0] => "1952/02/17"
// [1] => "生"
// }
$birthdateParts = $birthParts[0];
return $birthdateParts;
}