Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What means Call to a member function on boolean and how to fix

I'm new with cakePHP 3. I have created a controller and model where I call a function to get all users from the database. But when I run the code below I will get the following error "Call to a member function get_all_users() on boolean".

what does this error means and how can I fix this up?

User.php (model)

namespace App\Model\Entity;
use Cake\ORM\Entity;

class User extends Entity {

    public function get_all_users() {
        // find users and return to controller
        return $this->User->find('all');
    }
}

UsersController.php (controller)

namespace App\Controller;
use App\Controller\AppController;

class UsersController extends AppController {

    public function index() {
        // get all users from model
        $this->set('users', $this->User->get_all_users());
    }
}
like image 429
CodeWhisperer Avatar asked Aug 04 '15 15:08

CodeWhisperer


1 Answers

Generally this error happens when a non-existent property of a controller is being used.

Tables that do match the controller name do not need to be loaded/set to a property manually, but not even they exist initially, trying to access them causes the controllers magic getter method to be invoked, wich is used for lazy loading the table class that belongs to the controller, and it returns false on error, and that's where it happens, you will be calling a method on a boolean.

https://github.com/cakephp/.../blob/3.0.10/src/Controller/Controller.php#L339

In your case the problem is that User (singular, for entities) doesn't match the expected Users (plural, for tables), hence no matching table class can be found.

Your custom method should go in a table class instead, the UsersTable class, which you should then access via

$this->Users

You may want to reread the docs, entities do not query data (unless you are for example implementing lazy loading), they represent a dataset!

like image 154
ndm Avatar answered Nov 13 '22 17:11

ndm