从集合

时间:2017-05-20 06:18:23

标签: php laravel collections laravel-5.2

我一直在为我的Laravel应用程序构建自定义票证系统,用户可以对票证进行评论。

当发布新评论时,我想向参与故障单的所有人发送通知。

用户可以参与:

  • 机票所有者
  • 分配给故障单的代理
  • 作为参与者受邀参加

为此,我创建了一个用户集合,然后循环遍历它们以通知它们。唯一的问题是,它目前还包括发表评论的人,并且他们不需要收到通知,因为他们是留下评论的人。

如果ID与当前登录的用户匹配,我已尝试filter该集合删除用户,但这似乎无效:

$ticket = App\Ticket::findOrFail(1);

//Create collection to hold users to be notified
$toBeNotified = collect();

//Add the ticket owner
$toBeNotified->push($ticket->owner);

//If an agent is assigned to the ticket, add them
if(!is_null($ticket->assigned_to)) $toBeNotified->push($ticket->agent);

//Add any active participants that have been invited
$ticket->activeParticipants()->each(function($participant) use ($toBeNotified) {
    $toBeNotified->push($participant->user);
});

//Remove any duplicate users that appear
$toBeNotified = $toBeNotified->unique();

//Remove the logged in user from the collection
$toBeNotified->filter(function($user) {
    return $user->id != Auth::user()->id;
});

//...loop through each user and notify them

进一步阅读后,我认为这是因为您使用filter从集合中删除元素,而不是集合中的集合。

如果用户是当前登录的用户,如何从集合中删除用户?

运行上述内容后dd($toBeNotified),结果如下:

enter image description here

1 个答案:

答案 0 :(得分:1)

您可以使用except来实现此目标。

$toBeNotified = $toBeNotified->except(auth()->id());

作为旁注,如果要添加多个用户,则应使用合并。

$toBeNotified = $toBeNotified->merge($ticket->activeParticipants);

您使用的过滤方法也是正确的,但它会返回过滤后的集合,同时保持原始集合不变。

$toBeNotified = $toBeNotified->filter(function($user) {
    return $user->id != auth()->id();
});

编辑:只有当您拥有雄辩的收藏时,except才有效。