Skip to content

Commit

Permalink
Merge pull request cmgmyr#130 from DODMax/master
Browse files Browse the repository at this point in the history
Implemented unread threads as a relationship on Messagable Trait
  • Loading branch information
cmgmyr committed Jun 2, 2016
2 parents 7772cd7 + 4d5dd46 commit f71151d
Showing 1 changed file with 15 additions and 27 deletions.
42 changes: 15 additions & 27 deletions src/Cmgmyr/Messenger/Traits/Messagable.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,47 +44,35 @@ public function threads()
);
}

/**
* Unread threads as a relationship
*
* @return \Illuminate\Database\Eloquent\Relations\belongsToMany
*/
public function unreadThreads()
{
return $this->threads()
->whereRaw(Models::table('threads') . '.updated_at > '
. Models::table('participants') . '.last_read');
}

/**
* Returns the new messages count for user.
*
* @return int
*/
public function newThreadsCount()
{
return count($this->threadsWithNewMessages());
return $this->unreadThreads()->count();
}

/**
* Returns all threads with new messages.
* Returns the id of all threads with new messages.
*
* @return array
*/
public function threadsWithNewMessages()
{
$threadsWithNewMessages = [];

$participants = Models::participant()->where('user_id', $this->id)->lists('last_read', 'thread_id');

/**
* @todo: see if we can fix this more in the future.
* Illuminate\Foundation is not available through composer, only in laravel/framework which
* I don't want to include as a dependency for this package...it's overkill. So let's
* exclude this check in the testing environment.
*/
if (getenv('APP_ENV') == 'testing' || !str_contains(\Illuminate\Foundation\Application::VERSION, '5.0')) {
$participants = $participants->all();
}

if ($participants) {
$threads = Models::thread()->whereIn('id', array_keys($participants))->get();

foreach ($threads as $thread) {
if ($thread->updated_at > $participants[$thread->id]) {
$threadsWithNewMessages[] = $thread->id;
}
}
}

return $threadsWithNewMessages;
return $this->unreadThreads()->lists(Models::table('threads') . '.id');
}
}

0 comments on commit f71151d

Please sign in to comment.