1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Laravel】ゲッターについて

Last updated at Posted at 2018-07-26

ゲッターの使い方について整理。

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しか指定しなくてし、他のメソッドでの定義もする必要ないので楽です。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?