LoginSignup
2
1

More than 1 year has passed since last update.

【Laravel】 テーブルに無い属性を追加したい

Posted at

はじめに

テーブルのカラムにない項目をフロントに渡す必要があり、その方法を調べていた際に、とても便利だなと思ったものがあったため、備忘録として記事にしました。

今回行いたかったこと

customersテーブルからEloquentで取得する際に、カラムにない
action = 3;
という属性を追加し、JSONレスポンスに含めたい。

customersテーブル

ID first_name last_name
 1   田中  太郎

今回行ったこと

「アクセサ」と「ミューテタ」を使用し、予めデータの形式を定義しておきます。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public $table = 'customers';

    protected $appends = ['type'];  # ②

    public $fillable = [
        'id',
        'first_name',
        'last_name',
    ];

    public function getTypeAttribute()  # ①
    {
        return 3;
    }
}

解説

①独自属性を追加するには、getXXXXAttributeメソッドを定義する必要があります。
今回は、
getTypeAttribute
という関数を定義しています。

②ただこれだけでは、JSONレスポンスに定義した属性が含まれないため、$appendsを定義する必要があります。
今回は、
protected $appends = ['type'];
と定義しています。

その他にできること

今回のcustomersテーブルのように、「名字」と「名前」が別のカラムで管理されている場合、これまではフロントで「名字」と「名前」を結合して表示していましたが、「アクセサ」と「ミューテタ」を使用すれば、「氏名」としてJSONレスポンスでフロントにデータを渡すこともできます。
具体的には、以下のようになります。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public $table = 'customers';

     protected $appends = ['name']; # 追加

    public $fillable = [
        'id',
        'first_name',
        'last_name',
    ];

     public function getNameAttribute() # 追加
    {
        return $this->attributes['last_name'] . ' ' . $this->attributes['first_name'];
    }
}

まとめ

これまではフロント側で「名字」と「名前」を結合して、氏名を表示していました。
今回、「アクセサ」と「ミューテタ」を初めて知り、すごい便利だなと感じました。

参考にさせていただいたページ

2
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
2
1