session destory after login Yii2

Hello
i set shopping cart items of guest user in session and after calling Yii::$app->user->login, session data will be destroy, i need this data after login to save it in database.
what should i do?
please help me
thanks

Hi there,
Can you please provide some code of yours ?
how did you created SESSION for cart etc.
Thank You

this is my code:
$datas =[
‘price’ => ‘1000’,
‘stock’ => ‘20’,
‘modelClassName’ => ‘str’,
‘uniqueId’ => ‘2013444’,
‘modelTitle’ => ‘title’,
‘modelId’ =>‘23’,
‘quantity’ => 1,
];
webSession component is from yii\web\Session
and i set it as below:
Yii::$app->webSession->set(‘cart’, serialize($datas));
Yii::$app->webSession->get(‘cart’, false) return data before login but after login it return false!
another thing that i should say is that i use another session class for storing user data that issession component and is from \yii\web\DbSession for login users

Hi Mozhgan,

There are plenty ways to store cart item ,
like

  1. localstorage ,
  2. sessions,
  3. cookies
    and few more.

i recommend using cookies to store the cart items.
here you can find help for cookies storage
sessions-cookies

Regardless, if you want to store in SESSION
then you can do like this:

    $datas = [  ‘price’ => ‘1000’, ‘stock’ => ‘20’, ‘modelClassName’ => ‘str’, ‘uniqueId’ => ‘2013444’, ‘modelTitle’ => ‘title’, ‘modelId’ =>‘23’, ‘quantity’ => 1];
    $session = Yii::$app->session;

    $session->set('cart', $datas);  // or you can use   $session->set('cart', serialize($datas));  

this way you can set sessions and while you can to get these items back after login you can do like this

$session = Yii::$app->session;
$cart= $session->get('cart');

NOTE: Yii login function never destroy any custom sessions , but your code can do that,

Let me know if this is helpful.

Thank You

thanks for your help. your solution solved my problem

I glad to help you :slight_smile: