doumou5109 2017-01-16 23:45
浏览 52

没有从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.

  • 写回答

1条回答 默认 最新

  • doulu7174 2019-07-18 14:42
    关注

    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
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀