0

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??

0

2 Answers 2

0

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');
Sign up to request clarification or add additional context in comments.

3 Comments

and where to store quantity??
This post shows how we can store arrays inside an array. I was looking for associative array...
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.