LoginSignup
0
0

ミューテータとappend()

Last updated at Posted at 2023-12-23

はじめに

私は株式会社qnoteにて、勉強会の幹事を務めております。
2023年度勉強会の珠玉のネタを2023Qiitaアドベントカレンダーに投稿していこうと思います。

対象者

この記事は下記のような人を対象にしています。

  • 駆け出しエンジニア
  • プログラミング初学者

結論

ミューテータは便利なので使いましょう!
ただし、記述箇所は慎重に検討しましょう。

ミューテータの定義はモデルで

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Hoge extends Model
{

	public function getHugaHugaAttribute() // get + XX + Attributeで定義
    {
        return 'hugahuga';
    }
}

取得はappend()で

$hoge = Hoge::find(1)->append('huga_huga'); // append()の引数はスネークケース文字列で

print($hoge->huga_huga);

// 出力
'hugahuga'20

Hoge::where('id', 1)->get()->append('huga_huga'); // get()でも使える
Hoge::where('id', 1)->get()->toArray()->append('huga_huga'); // get()->toArrayでも使える
Hoge::first()->append('huga_huga'); // first()でも使える
Hoge::all()->append('huga_huga'); // all()でも使える
Hoge::append('huga_huga'); // Builderには使用できない!!!

append()なしで取得する場合はモデルに$appendsを定義

<?php
 
namespace App;
 
use Illuminate\Database\Eloquent\Model;
 
class Hoge extends Model
{
    /**
     * The accessors to append to the model's array form.
     *
     * @var array
     */
    protected $appends = ['huga_huga'];

		public function getHugaHugaAttribute()
	    {
	        return 'hugahuga';
	    }
}
$hoge = Hoge::first(1);
print($hoge->hoge_hoge);

// 出力
'hugahuga'

※モデルが使用される全ての箇所で使用されるので要注意。

おわりに

ミューテータとappend()についてまとめました。

参考記事

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