Wednesday, March 9, 2022

[FIXED] 'Error: Call to a member function allow() on a non-object' in CakePHP 3 AuthComponent

Issue

Following the CakePHP which looks a bit confusing and not so straight forward, I have created a basic authentication logic, however, I cannot seem to load Auth component.

Here is the code part from the AppController.php:

public function initialize()
{
    parent::initialize();

    $this->loadComponent('RequestHandler');
    $this->loadComponent('Flash');
    $this->loadComponent('Auth', [
            'authenticate' => ['Form' => ['fields' => ['username' => 'email', 'password' => 'password']]],
            'loginAction' => ['controller' => 'Users', 'action' => 'login'],
            'loginRedirect' => ['controller' => 'Groups', 'action' => 'index'],
            'logoutRedirect' => ['controller' => 'Users', 'action' => 'login']
    ]);  
}


//Allow basic views

public function beforeFilter(Event $event)
{
    $this->Auth->allow(['index', 'view', 'display']);
}

Now no matter which controller or action I run, I always receive the following error:

Error: Call to a member function allow() on a non-object 

that is referencing the following line:

$this->Auth->allow(['index', 'view', 'display']);

It has to be a straight forward thing, but I just cannot find it in the docummentation, therefore any help or guidance is much appreciated.


Solution

Check that your child controller's method initialize() is calling the parent method.

class MyController extends AppController
{
    public function initialize() {
        parent::initialize();
        //rest of code
    }
}


Answered By - Inigo Flores

No comments:

Post a Comment

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