Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

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

over 4 years ago · Santiago Trujillo
2 answers
Answer question

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');
over 4 years ago · Santiago Trujillo Report

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!