7

I am trying to understand the usage and difference of boot and booted.

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    protected static function boot() {
        parent::boot();

        static::creating(function ($user) {

        });
    }

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

        static::creating(function ($user) {

        });
    }
}

When and where should be this two function called?

parth
  • 1,803
  • 2
  • 19
  • 27
  • is a duplicate of https://stackoverflow.com/questions/24856157/laravel-where-to-add-booted-and-booting-callbacks ? – Alex Shchur Jul 20 '20 at 04:55
  • 2
    If I remember correctly, booted in a static array of booted models used in Illuminate/Database/Eloquent/Model.php and boot method is used in a model which is used to boot traits. – bhucho Jul 20 '20 at 04:55

2 Answers2

6

Actually answer is in the Eloquent model itself:

protected function bootIfNotBooted()
{
    if (! isset(static::$booted[static::class])) {
        static::$booted[static::class] = true;

        $this->fireModelEvent('booting', false);

        static::booting();
        static::boot();
        static::booted();

        $this->fireModelEvent('booted', false);
    }
}
/**
 * Perform any actions required before the model boots.
 *
 * @return void
 */
protected static function booting()
{
    //
}

/**
 * Bootstrap the model and its traits.
 *
 * @return void
 */
protected static function boot()
{
    static::bootTraits();
}

/**
 * Perform any actions required after the model boots.
 *
 * @return void
 */
protected static function booted()
{
    //
}
Sᴀᴍ Onᴇᴌᴀ
  • 8,218
  • 8
  • 36
  • 58
DominikStyp
  • 360
  • 6
  • 10
4

I tried both, I think there are just the same; just that boot will run first and it requires to call extra parent::boot()


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

    self::creating(function (Outlet $outlet): void {
        Log::debug("#boot");
        $outlet->name = "boot";
    });
    
}

protected static function booted()
{
    self::creating(function (Outlet $outlet): void {
        Log::debug("#booted");
        $outlet->name = "booted";
    });
    
}

Soo Xiao Tong
  • 144
  • 1
  • 6