ゲッターの使い方について整理。
getXXXXXAttributeメソッドを作ることでゲッターになるらしい。
userに紐づくpostの一覧から最新のものを取得する想定。
user.php
public function getPostAttribute()
{
$post = $this->orderBy('created_at', 'desc')->first();
return $post->name;
}
ユーザ一覧(user/index)で$userを定義する。
UserContoroller.php
class IndexController extends Controller
{
public function index(Request $request)
{
$users = User::all();
return view('user.index', [
'users' => $users,
]);
}
}
user/index.blade.php
@foreach ($users as $user)
$user->post
@endforeach
これでユーザごとの最新のpostを取得することができる。
Controllerではuserしか指定しなくてし、他のメソッドでの定義もする必要ないので楽です。