CakePHP 3: How to properly check if a user is logged in

richerlariviere picture richerlariviere · Jul 13, 2015 · Viewed 9.2k times · Source

In CakePHP 3, I found two ways to find if a user is logged in.

1st solution

if(!is_null($this->Auth->user('id'))){
        // Logged in
}

2nd solution

if (!is_null($this->request->session()->read('Auth.User.id'))) {
    // Logged in
}

I think the first one is better because it's short and concise.

Is there a better way to verify if a user is logged in?

I'm not looking for speed necessarily. I want a clean and expressive way to write it.

Answer

Kamoris picture Kamoris · Jul 13, 2015

I think the best way is just:

if ($this->Auth->user()) {...}