Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 542
richerlariviere Avatar asked Jul 13 '15 15:07

richerlariviere


2 Answers

I think the best way is just:

if ($this->Auth->user()) {...}
like image 186
Kamoris Avatar answered Oct 24 '22 03:10

Kamoris


You can do this using session() helper.

$loggeduser = $this->request->session()->read('Auth.User');
if(!$loggeduser) {
    $userID = $loggeduser['id'];
    $firstName = $loggeduser['first_name'];
}
like image 22
Faisal Avatar answered Oct 24 '22 05:10

Faisal