[英]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 创建组后,没有向用户 B、C 发送通知, D... 我已经在组模型中包含了use Notifiable
。 所以有什么问题? 我必须做的。
谢谢
据我所知,您正在执行以下代码:
$userINList
变量中有一个名称数组User
User
User
名中的所有空格User
添加到组并发送通知我们可以在这里进行很多改进。 例如,我们已经知道您希望通知哪些用户,因此您无需获取和比较所有用户。
首先, $userINList
要么是一个数组User
对象或数组User
id
的S -数组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));
});
超级简单:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.