Drazxier Drazxier - 1 year ago 76
PHP Question

Displaying Notifications Logic

I am building a social network with Laravel framework, and I have a Notifications System.

Basically whenever a user interacts with the website in these 5 different ways:

  1. User upvotes a Post.

  2. User comments in a Post.

  3. User upvotes a comment.

  4. User replies to a comment.

  5. User upvotes a reply.

A notification is added to notifications table for that user (the OP (original poster) for instance, if a user upvotes a comment, a notification is added for the user who owns that comment, and in that notifications table I have these configuration.


Hence basically I can get each logged In user's unread notifications by using command
which is an array consisting of all the information of notifications.

But here is my question. For instance 100 user upvotes one of the post of an OP, that would mean that if I loop through unread notifications array, I'll get 100 notifications, but instead I want something like this, 'last user who interacted with the post' . 'x' people have . 'interacted' with your post.'

But I am just not able to execute it, so far I have managed to count the number of notifications user will see by using this logic:

public function get_Notification_Count()
$total_notifications = Auth::user()->unreadNotifications;
$num_of_posts = array();
$num_of_comments = array();
$num_of_replies = array();
$num_of_upvoted_comments = array();
$num_of_upvoted_replies = array();
// $num_of_notifications = array();

foreach ($total_notifications as $notification) {
if ($notification->type == 'App\Notifications\UserUpvotedPost') {
array_push($num_of_posts, $notification->data['post_id']);
$num_of_posts = array_unique($num_of_posts);
if ($notification->type == 'App\Notifications\UserCommented') {
array_push($num_of_comments, $notification->data['post_id']);
$num_of_comments = array_unique($num_of_comments);
if ($notification->type == 'App\Notifications\UserReplied') {
array_push($num_of_replies, $notification->data['comment_id']);
$num_of_replies = array_unique($num_of_replies);
if ($notification->type == 'App\Notifications\UserUpvotedComment') {
array_push($num_of_upvoted_comments, $notification->data['comment_id']);
$num_of_upvoted_comments = array_unique($num_of_upvoted_comments);
if ($notification->type == 'App\Notifications\UserUpvotedReply') {
array_push($num_of_upvoted_replies, $notification->data['reply_id']);
$num_of_upvoted_replies = array_unique($num_of_upvoted_replies);

$num_of_notifications = count(array_merge($num_of_posts, $num_of_comments, $num_of_replies, $num_of_upvoted_comments, $num_of_upvoted_replies));

return $num_of_notifications;

Answer Source

I think your best bet would be to group the query:

Auth::user()->unreadNotifications()->select(\DB::raw('COUNT(*) as count'), 'type')

I haven't tested this, but give it a spin ;)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download