PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, February 21, 2022

[FIXED] Call to a member function find() on a non-object()

 February 21, 2022     cakephp, cakephp-3.0     No comments   

Issue

Having started with CakePHP 3.0 I find docummentation very confusing as by following the code snippets I have genertaed the following code:

    if($this->Auth->User('role') != 'Admin' ){
             $query = $users->find('all')
                ->where(['Users.group_id' => $this->Auth->User('group_id')]);
             $this->set('users', $this->paginate($query->all()));
    }else{
        $this->set('users', $this->paginate($this->Users));
    }

Which runs perfectly fine if user is an admin, howver if he is not, then the code breaks on this line: $query = $users->find('all')

The following message is being provided:

Call to a member function find() on a non-object 

The code is run in users controller.

Any help or guidance is much appreciated.


Solution

Try this instead:

if($this->Auth->User('role') != 'Admin' ){

    $options = [ 
            'conditions' => array(
                "Users.group_id" => $this->Auth->User('group_id')
            )];

         $query = $users->find('all', $options);


    $this->set('users', $this->paginate($query));
}else{
    $this->set('users', $this->paginate($this->Users));
}

I think your issue is that you are essentially calling 'find' incorrectly.

$query = $users->find('all') ->$options

(not your exact code, but essentially what you have done, to help compare to my solution) should be

$query = $users->find('all', $options)

with $options declared above. This is a much cleaner way (in my opinion at least) of managing find options, an can be reused if needed once they are set to a variable.



Answered By - Ash Betts
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing