Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete session in cakephp 3.0?

all code is in one controller

My code goes like this.

    public function login()
    {
    $session = $this->request->session();
    $session_event_id = $session->read('Events.event_id');
    $session_division_id = $session->read('Events.division_id');

    if(!$session_event_id || !$session_division_id) {
        $event_table = TableRegistry::get('Events');
        $event = $event_table->find('all', ['fields' => ['id'], 'order' => 'id desc'])->first();
        $session->write('Events.event_id', $event->id);
        $session_event_id = $session->read('Events.event_id');

        $division_table = TableRegistry::get('Divisions');
        $division = $division_table->find('all',['fields' => ['id'], 'conditions' => ['event_id' => $event->id]])->first();
        $session->write('Events.division_id', $division->id);
        $session_division_id = $session->read('Events.division_id');
    }
    }

By above code i am able to write and read session values but while logout i want to delete those session data

public function logout()
{    
    $session = $this->request->session();
    $this->$session->delete();
    return $this->redirect($this->Auth->logout());
}

Warning (4096): Object of class Cake\Network\Session could not be converted to string [APP/Controller/UsersController.php, line 56]

Notice (8): Object of class Cake\Network\Session to string conversion [APP/Controller/UsersController.php, line 56]

Error: Call to a member function delete() on a non-object File /var/www/html/MEX/src/Controller/UsersController.php

like image 559
Naresh Dudhat Avatar asked May 10 '26 08:05

Naresh Dudhat


2 Answers

You're looking for $this->request->session()->destroy();

http://book.cakephp.org/3.0/en/development/sessions.html#destroying-the-session

Just a tip - there's not much of a point for storing a variable $session for a function that small, where the reuse of $session isn't necessary. The only case I'd store $this->request->session(); in a variable is when I'm accessing the session for multiple read and writes all in the same function.

(As far as the error is concerned, @Eagle is correct in that you're referencing '$this' twice by the use of that stored variable.)

like image 192
Isaac Askew Avatar answered May 13 '26 03:05

Isaac Askew


Thank You for your supports and help finally i found solution of my problem by myself

    $session = $this->request->session();
    $session->delete('Events.event_id');
    $session->delete('Events.division_id');

by doing so, i am able to clear session data. Thank you

like image 26
Naresh Dudhat Avatar answered May 13 '26 03:05

Naresh Dudhat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!