DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Laravel boot multiple traits

Lets say you want to use multiple traits in your models to reuse common code such as applying UUIDs and settings global query scopes like this:


use HasUuid;
use HasTenant;
Enter fullscreen mode Exit fullscreen mode

Each of these traits has a boot method:

HasUuid :


trait HasUuid
{
    public function getIncrementing(): bool
    {
        return false;
    }

    public function getKeyType(): string
    {
        return 'string';
    }

    public static function boot()
    {
        static::creating(function (Model $model) {
            // Set attribute for new model's primary key (ID) to an uuid.
            $model->setAttribute($model->getKeyName(), Str::uuid()->toString());
        });
    }
}
Enter fullscreen mode Exit fullscreen mode

HasTenant:


trait HasTenant
{
    public static function boot()
    {
        if (auth()->check()) {
            $tenantId = auth()->user()->tenant_id;

            //assign when creating a record
            static::creating(function ($query) use ($tenantId) {
                $query->tenant_id = $tenantId;
            });

            //apply condition to all queries
            static::addGlobalScope('tenant', function (Builder $builder) use ($tenantId) {
                $builder->where('tenant_id', $tenantId);
            });
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

trying to run this will trigger an error:

Trait method App\Models\Traits\HasTenant::boot has not been applied as App\Models\User::boot, because of collision with App\Models\Traits\HasUuid::boot

This is because both traits are using a boot method, to solve this Laravel supports a bootTraitName for example HasTenant becomes bootHasTenant

Change both traits to use the bootTraitName like this:


trait HasUuid
{
    public static function bootHasUuid()
    {
Enter fullscreen mode Exit fullscreen mode

and


trait HasTenant
{
    public static function bootHasTenant()
    {
Enter fullscreen mode Exit fullscreen mode

Now they can be used together in a single model without causing any errors.

Laravel also supports initializeTraitName which can look like:


protected function initializeHasToken()
{
    $this->token = Str::random(100);
}
Enter fullscreen mode Exit fullscreen mode

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more