DBから取得した値を加工して簡単にViewで表示させたい時に使う。
例:DBのlast_name(姓)とfirst_name(名)を一行で表示させる。
【bladeに表示させたい時】
コントローラー
public function form()
{
$user = User::where('id',auth()->user()->id)
->with('office')
->first();
}
Userモデル
public function getFullNameAttribute() // get + キャメルケース + Attribute で書く
{
return $this->last_name.' '.$this->first_name;
}
blade
{{ $user->full_name }} // アクセサ名を小文字のスネークケースで書く
【inertiaを使ってvueに表示させたい時】
コントローラー
public function form()
{
$user = User::where('id',auth()->user()->id)
->with('office')
->first();
return Inertia::render('Office/Edit', [
'user' => $user, // userデータをinertiaを通じてvueに渡す
]);
}
Userモデル
protected $appends = [ // 配列やJSON表現へ常に付加
]; その中にアクセサで計算される値を含める場合には$appends必要とのこと
public function getFullNameAttribute() // get + キャメルケース + Attribute で書く
{
return $this->last_name.' '.$this->first_name;
}
vue
<script setup>
const user = usePage().props.user;
</script>
<template>
{{ $page.props.user.full_name }} // アクセサ名を小文字のスネークケースで書く
</template>
const user = usePage().props.user;
</script>
<template>
{{ $page.props.user.full_name }} // アクセサ名を小文字のスネークケースで書く
</template>
例:Userのデータを使って、リレーションを組んでいるOfficeテーブルのnameカラムを「user.office_name」でvueに表示できるようにする。
※リレーション + get〜Attribute
Userモデル
public function office() // Officeに対してリレーションを定義
{
return $this->belongsTo(Office::class);
}
protected $appends = [ // 配列やJSON表現へ常に付加
'office_name',
];
public function getOfficeNameAttribute() // get + OfficeName + Attribute で書く
{
return $this->office->name;
}
vue
<script setup>
const user = usePage().props.user;
</script>
<template>
{{ $page.props.user.office_name}} // アクセサ名を小文字のスネークケースで書く
</template>
const user = usePage().props.user;
</script>
<template>
{{ $page.props.user.office_name}} // アクセサ名を小文字のスネークケースで書く
</template>