Search code examples
laravellaravel-models

Laravel Model: boot on trait and model


I have some Laravel models using the next Trait which is calling the model's boot method:

<?php

namespace App\Traits;

use Illuminate\Support\Str;

trait Uuids
{
  /**
   * Boot function from Laravel.
   */
  protected static function boot()
  {
    parent::boot();
    static::creating(function ($model) {
      if (empty($model->{$model->getKeyName()})) {
        $model->{$model->getKeyName()} = Str::uuid()->toString();

        if ($model->consecutive) {
          $model->consecutive = $model->max("consecutive") + 1;
        }
      }
    });
  }

  /**
   * Get the value indicating whether the IDs are incrementing.
   *
   * @return bool
   */
  public function getIncrementing()
  {
    return false;
  }

  /**
   * Get the auto-incrementing key type.
   *
   * @return string
   */
  public function getKeyType()
  {
    return "string";
  }
}

But on one of the models I have a consecutive column which I need to autoincrement and I was doing that with the boot function in the model:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Order extends Model
{
  use HasFactory, Uuids;

  public static function boot()
  {
    parent::boot();
    self::creating(function ($model) {
      $model->consecutive = $model->max("consecutive") + 1;
    });
  }
}

The problem is that only the trait's boot() is being called. Is there another way fill the consecutive column of my model or call boot() method on both files?


Solution

  • The boot function in the Uuids will not be triggered. To fix this issue, there is an awesome hidden feature in Laravel that says if the function name in your trait is prefixed with boot and then suffixed with your Trait name like bootYourTraitName it will be booted with the boot model function:

    <?php
    
    namespace App\Traits;
    
    use Illuminate\Support\Str;
    
    trait Uuids
    {
      /**
       * Boot function from Laravel.
       */
      protected static function bootUuids()
      {
        static::creating(function ($model) {
          if (empty($model->{$model->getKeyName()})) {
            $model->{$model->getKeyName()} = Str::uuid()->toString();
    
            if ($model->consecutive) {
              $model->consecutive = $model->max("consecutive") + 1;
            }
          }
        });
      }
    }