我的用户模型有一个观察者。在我的观察者->创建的事件中我有一些代码。
public function created(User $user)
{
sendEmail();
}
因此,我们的想法是,当创建用户时,系统将向用户发送帐户已创建的电子邮件通知。
问题:当数据库进行播种时,它还会调用此方法“已创建”并向用户(位于种子中)发送电子邮件通知。 所以,我的问题是,我如何检查,可能在这个“创建”方法中,目前 Laravel 正在播种数据 -> 不发送电子邮件或不运行“创建”观察者方法。
尝试谷歌,发现了一些东西,但工作不正确。 像
YourModel::flushEventListeners();
之类的东西
您可以使用
YourModel::unsetEventDispatcher();
删除模型临时的事件侦听器。
如果您在同一执行中播种后需要它们,您可以读取调度程序,取消设置它们,然后再次设置它们。
$dispatcher = YourModel::getEventDispatcher();
// Remove Dispatcher
YourModel::unsetEventDispatcher();
// do stuff here
// Re-add Dispatcher
YourModel::setEventDispatcher($dispatcher);
namespace Database\Seeders;
use App\Models\Blog;
use Illuminate\Database\Seeder;
class BlogsTableSeeder extends Seeder
{
public function run()
{
Blog::withoutEvents(function () {
// normally
Blog::factory()
->times(10)
->hasUploads(1) //hasOne
->hasComments(2) //hasMany
->create();
});
}
}
您可以使用
WithoutModelEvents
trait 将事件静音
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
class SomeSeeder extends Seeder
{
use WithoutModelEvents;
public function run()
{
User::factory( 30 )->create();
}
}
或者你可以尝试
createQuietly
工厂的方法,例如
class SomeSeeder extends Seeder
{
public function run()
{
User::factory( 30 )->createQuietly();
}
}
您可以使用 saveQuietly() 函数https://laravel.com/docs/8.x/eloquent# saving-a-single-model-without-events 这允许您禁用单个模型的所有事件。
如果您想禁用单个模型的单个事件,请在此处阅读:http://derekmd.com/2019/02/conditionally-suppressing-laravel-event-listeners/
您只需将其添加到您的数据库播种器中即可
class DatabaseSeeder extends Seeder
{
public function run(): void
{
activity()->disableLogging();
Mail::fake();
Notification::fake();