From 2901f76a1192db6a5dfe2ab693e291d428b20087 Mon Sep 17 00:00:00 2001 From: miguel456 Date: Sat, 15 Oct 2022 19:58:43 +0100 Subject: [PATCH] refactor(listeners): remove big n+1 query in user notifications Signed-off-by: miguel456 --- app/Listeners/OnUserRegistration.php | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/app/Listeners/OnUserRegistration.php b/app/Listeners/OnUserRegistration.php index f2fa814..c866cd5 100755 --- a/app/Listeners/OnUserRegistration.php +++ b/app/Listeners/OnUserRegistration.php @@ -49,10 +49,11 @@ class OnUserRegistration // TODO: Send push notification to online admins via browser (w/ pusher) Log::info('User '.$event->user->name.' has just registered for an account.'); - foreach (User::all() as $user) { - if ($user->hasRole('admin')) { - $user->notify(new NewUser($event->user)); - } - } + User::whereHas('roles', function ($q) { + $q->where('name', 'admin'); + })->get()->each(function ($user, $key) use ($event) { + $user->notify(new NewUser($event->user)); + }); + } }