Difference between boot and booted in laravel

Viewed 4593

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?

2 Answers

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()
{
    //
}

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

Related