LoginSignup
0
0

More than 3 years have passed since last update.

Laravelのアクセサの注意点について

Posted at

みなさんこんにちは tyamahoriです。
仕事でちょっとしたシステムをLaravelで作成する機会がありました。その中で注意しなければいけない点があったのでここに書き残したいともいます。

アクセサを使う際のメソッド名の命名には注意

getHogeHogeAttribute をモデル内に記載しているかと思います

具体例はこちらです。
まずはカラム名そのままになんのひねりもなくアクセサを使ってみます。

SampleEloquent.php

class SampleEloquent extends Model
{
    protected $table = 'sample_tables';

    /**
     * nameを取得するアクセサ
     *
     * @return string
     */
    public function getNameAttribute(): string
    {
        return $this->attributes['name'];
    }
}

次の例では注意が必要です

SampleEloquent.php
class SampleEloquent extends Model
{
    protected $table = 'sample_tables';

    /**
     * idカラムをhex形式で取得するアクセサ
     *
     * @return string
     */
    public function getIdAttribute(): string
    {
        return bin2hex($this->attributes['id']);
    }
}

上記の場合ですと、場合によっては挙動がおかしくなります。自分が経験したポイントを以下にまとめます。

ポイント

  • 何かしらの処理をアクセサに噛ませる場合は、getColumnNameAttribute() ではなく、getSomeActionColumnNameAttribute() にしておく
  • 特に、デーブルのリレーションで使われるカラムに何かしらの処理を絡ませるアクセサをつける場合は気をつける。getColumnNameAttribute()にするとバグる
  • traitでModel間の共通処理を作って、アクセサを使う場合もgetColumnNameAttribute()は避ける。getSomeNameColumnNameAttribute()みたいな命名にする。

まとめ

アクセサのメソッド名の命名には気を使いましょう。思わぬところで変なバグを生みます。それでは良きLaravelライフを~

0
0
1

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
0
0