3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

LaravelのModel(Eloquent)で取得時のデフォルト値を指定する

Last updated at Posted at 2019-01-20

よく忘れて探すのでメモ。

User.php
class User extends Authenticatable
{
    use Notifiable;
    protected static function boot()
    {
        parent::boot();
        User::retrieved(function($user) {
            if(!$user->profile_image_url){
                 $user->profile_image_url = asset('/img/default_profile_image.png');
            }
        });
    }
}

上記はDBにないデータが渡ってきて混乱するので、
このやり方するよりは下記のようにModel生成時にデフォルト値を指定する方法をおすすめします。

User.php
class User extends Authenticatable
{
    use Notifiable;
    protected static function boot()
    {
        parent::boot();
        User::creating(function($user) {
            $user->profile_image_url = asset('/img/default_profile_image.png');
        });
    }
}

あとで見てて気づいたのですが、下記のような方法もあるみたいです。

User.php
class User extends Authenticatable
{
    use Notifiable;

    protected $attributes = [
        'profile_image_url' => asset('/img/default_profile_image.png'),
    ];
}
3
3
2

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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?