LoginSignup
3
0

More than 3 years have passed since last update.

Laravelのミューテタはfillableに設定できるか

Last updated at Posted at 2019-10-09

タイトル通り。

結論としては使えます。

※Laravel:6.0.3

サンプル

class User extends Model
{
    protected $fillable = [
        'name',
        'age'
    ]
}
>>> App\User::create(["name" => "hoge", "age" => 99])
=> App\User {
     id: 1,
     name: "hoge",
     age: 99,
     updated_at: "2019-10-09 10:20:33",
     created_at: "2019-10-09 10:20:33",
   }

ミューテタを追加

class User extends Model
{
    protected $fillable = [
        'name',
        'age',
        'birthday'
    ]

    public function setBirthdayAttribute($value)                                                                                      
    {                                                                                                                                 
        $this->attributes['age'] = CarbonImmutable::parse($value)->age;                                                      
    } 
}

birthdayの方で作ってみる

>>> App\User::create(["name" => "fuga", "birthday" => "2000-04-01"])
=> App\User {
     id: 2,
     name: "fuga",
     age: 19,
     updated_at: "2019-10-09 10:35:48",
     created_at: "2019-10-09 10:35:48",
   }

fillableに残っているのでageもそのまま使える

>>> App\User::create(["name" => "piyo", "age" => 50])
=> App\User {
     id: 3,
     name: "piyo",
     age: 50,
     updated_at: "2019-10-09 10:36:01",
     created_at: "2019-10-09 10:36:01",
   }

birthdayで必ず作りたいならfillableからageを外してしまえばokです。

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