nahid / talk

Talk is a real-time users messaging and chatting system for Laravel.
MIT License
1.61k stars 327 forks source link

Get Inbox Unread Count #70

Open packytagliaferro opened 7 years ago

packytagliaferro commented 7 years ago

Is there a better way of getting the inbox count?

Right now I have this in my User model and load it in the head to a JS object so I can use it in a view component.

User Model:

public function inboxcount()
    {

      $user_id = Auth::user()->id;

      Talk::setAuthUserId($user_id);

      $inboxes = Talk::getInbox();

      $unread  = 0;

      //Get the unread thread count
      foreach ( $inboxes as $inbox ) {
        if($inbox->thread->is_seen == false && $inbox->thread->sender->id != $user_id){
          $unread  += 1;
        }
      }

      return $unread;

    }

head.php:

<script>

    window.Logic = {!! json_encode([
        'csrfToken' => csrf_token(),
        'stripeKey'=> config('services.stripe.key'),
        'user'=> Auth::user() ? Auth::user()->load('roles') : null,
        'inbox'=> Auth::user() ? Auth::user()->inboxcount() : null,
    ]) !!};

</script>

Then Finally in my Navigation I use it in a vue component:

<badge :inboxcount='window.Logic.inbox'></badge>

Doing it this way the $inboxes = Talk::getInbox(); does a query for every message. So right now its 5 queries for just 2 messages. If a user has a big inbox it could get bigger I imagine.

screen shot 2017-06-13 at 8 53 32 pm
mohfrea commented 6 years ago

Although it's too late to post something on this issue, however maybe for the new users it can help. This is a small hack to get the number of "Unread Messages" of each conversation for each user. add the following function to "Message.php" model:

 public function getNumberOfUnreadMessagesAttribute()
    {
      return DB::table('messages')->select('id')->where('user_id','!=',Auth::user()->id)->where('conversation_id',$this->conversation->id)->where('is_seen',0)->count();
    }

Then u can access it this way

Message->NumberOfUnreadMessages

I hope it helps.

ayushmall0710 commented 6 years ago

Thank you very much @mohfrea! You're a true lifesaver!!