cakephp error Call to a member function find() on null

144 Views Asked by At

i am trying to count unique views of a post but i keep getting this error ( Call to a member function find() on null ) I've tried another way than find like select and distinct but nothing changes here is my view method in the PostController.php :

public function view($id = null) {
    $user_id = $this->Auth->user('id');
    $ip_address = $this->request->clientIp();

    $post = $this->Post->findById($id);

    if ($post) {
        $this->Post->incrementViews($id, $ip_address, $user_id);
        $this->set('post', $post);
    } else {
   
        $this->Flash->error(__('The post you requested could not be found.'));
        $this->redirect(array('action' => 'index'));
    }

    $uniqueViews = $this->Post->find('count', array(
        'conditions' => array(
            'Post.id' => $id,
        ),
        'joins' => array(
            array(
                'table' => 'views',
                'alias' => 'views',
                'type' => 'INNER',
                'conditions' => array(
                    'views.post_id = Post.id',
                    'views.user_id IS NOT NULL'
                )
            )
        ),
        'group' => array('views.user_id')
    ));
    $this->set(compact('uniqueViews'));
    if (!$id || !$post) {
        throw new NotFoundException(__('Invalid post'));
    }
}

and here is the method in the Post.php model :

 public function incrementViews($id, $ip_address, $user_id = null) {
            $view = $this->Views->find('first', array(
                'conditions' => array(
                    'Views.post_id' => $id,
                    'Views.ip_address' => $ip_address,
                    'Views.user_id' => $user_id
                )
            ));
        
        
            if ($view) {
                $this->Views->id = $view['Views']['id'];
                $this->Views->saveField('view_count', $view['Views']['view_count'] + 1);
                $this->Views->saveField('last_viewed', date('Y-m-d H:i:s'));
            } else {
                // Otherwise, create a new view record for the post and IP
                $this->Views->create();
                $this->Views->save(array(
                    'post_id' => $id,
                    'ip_address' => $ip_address,
                    'user_id' => $user_id,
                    'view_count' => 1,
                    'last_viewed' => date('Y-m-d H:i:s')
                ));
            }
        
            // Update the view count for the post
            $this->id = $id;
            $this->saveField('views', $this->field('views') + 1);
        }
1

There are 1 best solutions below

0
IrfanAnwar On

Override $uses e.g $uses =['POST'] at the beginning of your controller.