public function scopeUnreadForUser(Builder $query, $userId)
    {
        return $query->has('thread')
            ->where('user_id', '!=', $userId)
            ->whereHas('participants', function (Builder $query) use ($userId) {
                $query->where('user_id', $userId)
                    ->whereNull('deleted_at')
                    ->where(function (Builder $q) {
                        $q->where('last_read', '<', $this->getConnection()->raw($this->getConnection()->getTablePrefix() . $this->getTable() . '.created_at'))
                            ->orWhereNull('last_read');
                    });
            });
    }
public function scopeUnreadForUser(Builder $query, $userId)
    {
        return $query->has('thread')
            ->where('user_id', '!=', $userId)
            ->whereHas('participants', function (Builder $query) use ($userId) {
                $query->where('user_id', $userId)
                    ->whereNull('deleted_at')
                    ->where(function (Builder $q) {
                        $q->where('last_read', '<', $this->getConnection()->raw($this->getConnection()->getTablePrefix() . $this->getTable() . '.created_at'))
                            ->orWhereNull('last_read');
                    });
            });
    }
public function scopeUnreadForUser ( Builder $ query , $ userId ) { return $ query -> has ( 'thread' ) -> where ( 'user_id' , '!=' , $ userId ) -> whereHas ( 'participants' , function ( Builder $ query ) use ( $ userId ) { $ query -> where ( 'user_id' , $ userId ) -> whereNull ( 'deleted_at' ) -> where ( function ( Builder $ q ) { $ q -> where ( 'last_read' , '<' , $ this -> getConnection ( ) -> raw ( $ this -> getConnection ( ) -> getTablePrefix ( ) . $ this -> getTable ( ) . '.created_at' ) ) -> orWhereNull ( 'last_read' ) ; } ) ; } ) ; }
Returns unread messages given the userId.

@param \Illuminate\Database\Eloquent\Builder $query
@param int $userId
@return \Illuminate\Database\Eloquent\Builder
Returns unread messages given the userId .