CakePHP 4: How to read session data in table class(Model)?

Viewed 506

I have upgraded CakePHP from version 3.6 to 4.0, in version 3.6 i can access session in model using following workaround,

use Cake\Network\Session;
public function getSessionUser() {
    $session = new Session();
    return $session->read('Auth.User');
}

Now problem is that in newer version 4.0 , it is giving error "Class 'Cake\Network\Session' not found".

Can anyone help how to access session in model in cakephp 4 version ?

Thanks

3 Answers

I found the solution. First, you need to use the below line in starting of class

use Cake\Routing\Router; 

Then simply create an object of session like this

$session = Router::getRequest()->getSession(); 

and then you read the session in table class

$session->read("key");

I have found solution is that change use Cake\Network\Session to use Cake\Http\Session in model.

Related