LoginSignup
1
1

More than 3 years have passed since last update.

【Laravel】アクセサを使う

Posted at

はじめに

例えば、ユーザーの投稿数を取得したい時がある。
その場合、Laravelのアクセサを使えば、テーブルのカラムのように簡単に取得することができる。

アクセサを使う

先程の例でいくと、アクセサを使わない場合はこんな感じで記述する。

view
{{ $user->posts()->count() }}  

このままだと少し冗長でわかりにくいので、アクセサを使い、シンプルにする。

アクセサを使うときは、モデルにget~Attributeというメソッドを作成する。

User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    // 省略

    /**
     * 記事の投稿数を取得
     *
     * @return integer
     */
    public function getCountPostsAttribute()
    {
        return this->posts->count();
    }
}

このアクセサをControllerやviewで呼び出す場合は、getAttributeを取り除いたスネークケースで記述する。

view
{{ $user->count_posts }}

モデルのプロパティ(テーブルのカラム)のように使えるので、シンプルでわかりやすい。

おまけ

JSONレスポンスの場合は、$appendsを定義する必要がある。

    /**
    * モデルの配列形態に追加するアクセサ
    *
    * @var array
    */
    protected $appends = ['count_posts'];   // 追加

    /**
    * 記事の投稿数を取得
    *
    * @return integer
    */
    public function getCountPostsAttribute()
    {
        return this->posts->count();
    }

参考

https://readouble.com/laravel/7.x/ja/eloquent-mutators.html
https://qiita.com/shonansurvivors/items/cd7ee1c038f9543eab8f

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