Code/PHP

Laravel Model의 boot()

kolbe_starziki 2021. 2. 28. 08:35

 

laravel-news.com/eloquent-tips-tricks

 

20 Laravel Eloquent Tips and Tricks

Eloquent ORM seems like a simple mechanism, but under the hood, there’s a lot of semi-hidden functions and less-known ways to achieve more with it. In this article, I will show you a few tricks.1. Increments and DecrementsInstead of this:$article = Artic

laravel-news.com

3. Momdel  boot() method

Eloquent 모델을 기본행동을 재정의하는 곳을 'boot()'라 한다.

class User extends Model
{
    public static function boot()
    {
        parent::boot();
        static::updating(function($model)
        {
            // do some logging
            // override some property like $model->something = transform($something);
        });
    }
}

아마도 가장 인기있는 예는 모델객체가 만들어질 때, 필드를 세팅하는 것이다.

다음과 같이 UUID필드를 초기화 할 있다.

public static function boot()
{
  parent::boot();
  self::creating(function ($model) {
    $model->uuid = (string)Uuid::generate();
  });