Laravel Model: boot on trait and model

4.3k Views Asked by At

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?

1

There are 1 best solutions below

0
On BEST ANSWER

The boot function in the Uuids will not be triggered and to fix this issue, there is an awesome hidden feature in Laravel that says if the function name in your trait was bootYourTraitName it will be triggered with the boot model function, like so

<?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;
        }
      }
    });
  }
}