2

It may be hard to explain this case via title so let me put it here.

I had to use Laravel Boilerplate. It uses UUIDs for models. It has a trait that when User model is being created, it adds UUID.

protected static function boot() // this is in the trait
{
    parent::boot();

    static::creating(function ($model) {
        $model->{$model->getUuidName()} = PackageUuid::generate(4)->string;
    });
}

My Eloquent User uses this trait. Everything was working but one day I had to add global scope to User so I defined in the User class:

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

    static::addGlobalScope(new UserScopeSalesContactAdmin());
}

enter image description here

I totally missed that. Now my global scope works but UUID is ignored. I obviously know why this happens. I'm not the author of the Boilerplate and I would architecture this in a different way but it's a nice educational case hence my question:

How can I change my code the way that both my global scope works as well as UUID? I could simply move my addGlobalScope to the trait but it's obviously stupid idea as scope has nothing to do with UUID hence it violates the OOP rule.

edit:

I did other way around: I copied:

static::creating(function ($model) {
     $model->{$model->getUuidName()} = PackageUuid::generate(4)->string;
});

to the boot method in the User but still I consider this as a duplication…

2 Answers 2

2

You can write your own trait. But instead of boot() define boot<TraitName>():

trait HasUuid
{
    protected static function bootHasUuid()
    {
        static::creating(function ($model) {
            $model->{$model->getUuidName()} = PackageUuid::generate(4)->string; 
        });
    }
}

This way you don't need to override boot().

Laravel will call the special boot method of traits based on the naming scheme described above. It's just not well documented functionality...

Sign up to request clarification or add additional context in comments.

Comments

0

You can try this assuming the name of the trait is BoilerplateTrait. Call the BoilerplateTrait boot function from inside the boot function of you User model

protected static function boot()
{
    //parent::boot();
    BoilerplateTrait::boot();
    static::addGlobalScope(new UserScopeSalesContactAdmin());
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.