简体   繁体   中英

Storing associative array in session variable laravel

Actually, I am creating a shopping cart. I need to store the product_id and the quantity in the session, so that I can retrieve these into the Cart page.

Currently, I am adding values to the session variable using the push method-

$request->session()->push('order.products', $request->product_id);

It stores data in this structure-

array (size=1)
      'products' => 
        array (size=2)
          0 => string '11' (length=2)
          1 => string '9' (length=1)

But, in this way I am not able to store the quantity. I think storing associative array into the session can solve my problem.

So, how can I do that??

Please try it.

// store data in session.

   $request->session()->push('productsid', ['order.products'=>$request->product_id]);

// then get session data here.
$array = Session::get('productsid');

The Laravel didnt provided this feature but you can achieve what you want within a function:

/**
 * this method will append new values to session stored array,
 *
 * This method functionality has advantage over Laravel's session()->push is:
 * it can accept an associate array as well as normal array
 *
 * @param  string $session_key    the session key which associated with The 'Array'
 * @param  array $appendingArray The array which will be append to existing session-stored array
 * @return void
 */
private static function session_append($session_key, $appendingArray)
{
    session()->put($session_key, array_merge(
        session()->get($session_key),
        $appendingArray
    ));
}

and as long as it depends on session() helper, it can be a global helper as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM