laravel / ideas

Issues board used for Laravel internals discussions.
938 stars 28 forks source link

Eloquent model "constructed" event #2541

Closed JakeBooher closed 3 years ago

JakeBooher commented 3 years ago

This event would likely fire at the end of __construct and would be helpful to define default values that are dynamic, and need to be set when the model is instantiated. For example, if you have a multitenant application with separate sites you could autopopulate a site_id attribute based on however that is detected (Request header on an API, the domain, etc). For example:

    public static function bootSiteContentTrait(): void
    {
        static::registerModelEvent('constructed', function(Model $model) {
            if (Core::site() && !$model->exists && !$model->site_id) {
                $model->site_id = Core::site()->id;
            }
        });
    }
tpetry commented 3 years ago

Is there a specific reason you can't use the creating event?

public static function booted(): void
{
    static::creating(fn ($model) => $model->site_id = $model->site_id ?? Core::site()->id);
}