Andreas Witte
Andreas Witte

Reputation: 291

Cakephp3: $this->Auth->user('id') in AppController

I got stuck at a certain problem with the use of $this->Auth->user('id') in AppController. It returns following Error: Error: Call to a member function user() on null

Now what I want to do: I want to force everybody to get a proper profile. So I created the function forceprofile() in AppController. I ask this function to be Executed in AppControllers beforefilter-function. So it will be executed every time. When there is no profile, the user will be redirected from the forceprofile-function into a form, where he can save his profile.

In the very first code line of this forceprofile-function, directly after some comments, I take the UserID into a variable:

$userid = $this->Auth->user('id');

This is where the Error occurs.

Than I wanted to check out what happened there, I replaced the line by

debug($this->Auth->user('id')); die;

The result was:

int(1)

So actually I am getting a very proper result there.

The Stack of the original fault didn't provide any useful informations, it just prints [internal function] without any context or code... And it prints the BaseErrorHandler.

Anyone any idea, why debug() returns a proper result and asking the id to be assigned to a variable doesn't?

Thank you for your help.

Upvotes: 0

Views: 238

Answers (1)

Andreas Witte
Andreas Witte

Reputation: 291

I fixed the Problem myself now.

The function was called multiple times, because of loading multiple Controllers, doing callbacks, using Cells or whatever. I moved calling to this forceprofile function it to AppController::initialize(). Solved it.

Still it remains unclear for me, why executing the same code double (even if unintentionally) does not bring the same variables for usage.

Upvotes: 2

Related Questions