在 Laravel 5.5 后向用户发送通知

Send a notification to user in Laravel 5.5

场景是这样的。我有用户 A,通过通知向其他用户 B、C、D 发送……加入群组的请求。所以在 laravel 我创建了迁移和控制器来处理通知。

这是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));

                }
            }

        }

...

所以在$notification我会尝试传递收到邀请的用户的id,然后我使用notify()方法发送通知,但是在用户A创建了组之后没有't 通知用户 B、C、D... 我已将 use Notifiable 包含在组模型中。所以有什么问题?我必须做的。

谢谢

据我所知,您正在执行以下代码:

  1. $userINList 变量中有一个名称数组
  2. 你遍历数组中的每个名字
  3. 删除名称中的所有空格
  4. 检索每个 User
  5. 遍历每个 User
  6. 删除 User 名称中的所有空格
  7. 比较两个名字
  8. 如果比较通过,那么您将 User 添加到群组并发送通知

这里我们可以做很多改进。例如,我们已经知道您希望通知哪些用户,因此您无需获取和比较所有用户。

首先,$userINList 应该 User 个对象的数组或 User id 个对象的数组 — User 个对象的数组更好。然后你可以简单地遍历每一个。

例如,如果您有一个 ID 数组,那么您可以这样做:

$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));
    });

如果你有一个对象数组,那就更容易了,你可以这样做:

$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));
});

超级简单:-)