Model Boot Events

Posted: 2016-11-20 18:34:15

Just a quick not to modify model data upon an event. Laravel docs talk about it here

But putting it in another class can get kinda confusing when you are trying to debug or update the code.

In this example I have a model Board and I want to, upon saving, make sure it has some key data.

    protected static function boot()
    {
        static::bootTraits();

        /** @var \App\Board $model */
        static::creating(function ($model) {
            if (!$model->id) {
                $model->id = Uuid::uuid4()->toString();
            }
        });
    }

So now my \App\Board class will trigger this addition of UUID if the ID is not set upon creation.