Using a Trait to apply a global scope

Published 5 days ago by russellwwest

Currently I have a global scope that filters models by the logged in user’s account_id. I have used an interface to make sure I implement the boot method on the models I need it on. This works perfectly fine, but is quite repetitive.

So I’d like to know how to implement this global scope through a trait, just like laravel’s own soft deletes trait.

Any tips or helpers in the right direction would be much appreciated?

Thanks

bobbybouwmann

You can create a static method in your trait that starts with boot and then it will be applied automatically by Laravel. Below is the softDeletes example.

public static function bootSoftDeletes()
{
    static::addGlobalScope(new SoftDeletingScope);
}

So in you your case you might have something like this

public static function bootMyAction()
{
    static::addGlobalScope(new MyAction);
}

Tutorial: https://www.archybold.com/blog/post/booting-eloquent-model-traits

russellwwest

Perfect!! Works a charm. With this I will now try and work how to add a create observer in the trait.

Thanks for your help

martinbean

@russellwwest Be warned—by someone who has done this in the past—that this becomes a pain if you try and use your models in another context, such as console commands (where there is no session and therefore no authenticated user) and admin panels where you don’t want your models scoped by the current user.

Please sign in or create an account to participate in this conversation.