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:
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:
You can use except
to achieve this.
$toBeNotified = $toBeNotified->except(auth()->id());
As a side note you should use merge when you want to add more than one user.
$toBeNotified = $toBeNotified->merge($ticket->activeParticipants);
The filter method you use is correct as well, but it returns the filtered collection while keeping the original collection unchanged.
$toBeNotified = $toBeNotified->filter(function($user) {
return $user->id != auth()->id();
});
Edit: The except
would work only when you have an eloquent collection.