I've been building a custom ticket system for my Laravel application, and users can place comments on their tickets.
When a new comment is placed, I want to send a notification to everyone involved in the ticket.
Users can be involved if they are:
- the ticket owner
- the agent assigned to the ticket
- invited as a participant to the ticket
To do this, I am creating a collection of users and then looping through them to notify them. The only issue with this is that it currently includes the person making the comment too, and they don't need to be notified as they were the ones leaving the comment.
I've tried to filter
the collection to remove the user if the id matches the currently logged in user, but this doesn't seem to work:
$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
Upon further reading, I think this is because you use filter
to remove an element from a collection, rather than a collection that is inside a collection.
How can I remove a user from the collection if they are the currently logged in user?
When I dd($toBeNotified)
after running the above, this is the result: