【问题标题】:Send a notification to user in Laravel 5.5在 Laravel 5.5 中向用户发送通知
【发布时间】:2018-07-16 19:44:03
【问题描述】:

这就是场景。我有用户 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 创建了组并且没有通知到用户 B、C、D... 我已将use Notifiable 包含在组模型中。所以有什么问题?我必须做的。

谢谢

【问题讨论】:

    标签: php laravel notifications laravel-5.5


    【解决方案1】:

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

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

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

    首先,$userINList 应该要么User 对象数组或 User ids 数组 — 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));
    });
    

    超级简单:-)

    【讨论】:

    • 我修改了您的第一个示例,现在一切正常。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2017-08-19
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 1970-01-01
    • 2017-04-08
    • 1970-01-01
    相关资源
    最近更新 更多