Reputation: 119
This is the scenario. I've User A that send via notification to other User B,C,D... a request to join a group. So in laravel I've created the migration and the controller to handle the notification.
This is the code of GroupController
...
foreach ($userINList as $userIN) {
$userIN = str_replace(' ', '', $userIN);
$userDBList = User::all();
foreach ($userDBList as $userDB) {
$name = $userDB->last_name . $userDB->first_name;
$name = str_replace(' ', '', $name);
if (strcmp($name, $userIN) == 0) {
$newGroup->users()->attach($userDB->id, ['role' => 'member', 'state' => 'pending']);
$notification = User::find($userIN->id);
$notification->notify(new GroupNotification($newGroup));
}
}
}
...
So in $notification
I'll try to pass the id of Users that receive the invite and then I use the notify() method to send the notification, but after User A created the group and there aren't notifications to User B, C, D...
I've included the use Notifiable
in group model. So what's the problem? What I've have to do.
Thanks
Upvotes: 1
Views: 3176
Reputation: 5599
As far as I can tell from the code you're doing the following:
$userINList
variableUser
User
User
's nameUser
to the group and send a notificationThere are quite a few improvements we can make here. For example, we already know which users you wish to notify so you do not need to fetch and compare all users.
Firstly, $userINList
should either be an array of User
objects or an array of User
id
s — an array of User
objects is better. Then you can simply iterate through each one.
For example, if you have an array of ids then you could do this:
$group = Group::find(1);
$userINList = [1, 2, 3, 4];
User::whereIn('id', $userINList)
->get()
->each(function ($user) use ($group) {
$group->users()->attach($user->id, [
'role' => 'member',
'state' => 'pending'
]);
$user->notify(new GroupNotification($group));
});
And if you had an array of objects it would be even easier, you could do this:
$group = Group::find(1);
collect($users)->each(function ($user) use ($group) {
$group->users()->attach($user->id, [
'role' => 'member',
'state' => 'pending'
]);
$user->notify(new GroupNotification($group));
});
Super simple :-)
Upvotes: 1