没有从CLI(Laravel外)发射的雄辩事件

I have the following event handler in my model:

<?php
namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    //...

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

        static::saving(function ($user) {
            // die('inside');
            if (empty($user->username)) {

                $base = strtolower($user->first_name . '.' . $user->last_name);

                do {
                    $username = $base . @$suffix;
                    $duplicate = User::where('username', '=', $username)->first();
                } while($duplicate and $suffix = rand(1000, 9999));

                // return the original/ generated username
                $user->username = $username;
            }
        });
    }
}

Basically when username is not set, the model will automatically generate a unique username from the first/last name. This works fine in the browser. But not in the CLI when I'm running my tests - username is not set, so it attempts to insert without username which my mysql table doesn't accept.

Below is how I'm setting up Eloquent console:

$capsule = new \Illuminate\Database\Capsule\Manager;
$capsule->addConnection([
            'driver' => 'mysql',
            'host' => 'localhost',
            'charset' => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix' => '',
            'database' => 'sso_dev',
            'username' => 'root',
            'password' => 'vagrant1',
        ]);
$capsule->setEventDispatcher( new \Illuminate\Events\Dispatcher( new \Illuminate\Container\Container ));
$capsule->bootEloquent();
$capsule->setAsGlobal();

Both the web environment and testing use this same code. If I comment the line setEventDispatcher then the browser environment throws an error as the event handler doesn't fire. So I know the event dispatcher is doing it's job there. Just not the testing CLI environment. Any reason why this might be?

Btw I'm using Eloquent 5.3.

You will need to make a call to the setEventDispatcher again when it boots.

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

    static::setEventDispatcher(new \Illuminate\Events\Dispatcher());
    static::saving(function ($model){
        // now you can reference your model
    }
}