[英]Send a notification to user in Laravel 5.5
This is the scenario.这就是场景。 I've User A that send via notification to other User B,C,D... a request to join a group.
我有用户 A 通过通知发送给其他用户 B、C、D...加入一个组的请求。 So in laravel I've created the migration and the controller to handle the notification.
所以在 laravel 中,我创建了迁移和控制器来处理通知。
This is the code of GroupController这是 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.因此,在
$notification
我将尝试传递收到邀请的用户的 id,然后使用 notify() 方法发送通知,但是在用户 A 创建组后,没有向用户 B、C 发送通知, D... 我已经在组模型中包含了use Notifiable
。 So what's the problem?所以有什么问题? What I've have to do.
我必须做的。
Thanks谢谢
As far as I can tell from the code you're doing the following:据我所知,您正在执行以下代码:
$userINList
variable $userINList
变量中有一个名称数组User
User
User
User
User
's nameUser
名中的所有空格User
to the group and send a notificationUser
添加到组并发送通知There 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.首先,
$userINList
要么是一个数组User
对象或数组User
id
的S -数组User
对象是更好的。 Then you can simply iterate through each one.然后你可以简单地遍历每一个。
For example, if you have an array of ids then you could do this:例如,如果你有一个 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));
});
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 :-)超级简单:-)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.