0

I was trying to store some data in session through ajax. Means from Ajax request i would get the product_id and it put it inside product array through Session. And I want to retrieve every session array data.

Every Ajax request product_id will be stored into Session Array: // for storing $products into session following controller .But it stored only last one not the previous request

public function postEnquote(Request $request)
    {
       $product = Product::where('id',$request->Input(['product_id']))->first();
       Session::put('product', $product);
    }

// For retrieving every session data i used following one, but doesn't work properly means i couldn't get every session data..

  public function enquoteList()
    {
      foreach(Session::get('product') as $test)
      {
         var_dump($test->id);
      }

     }
3
  • Why not just use the $_SESSION superglobal directly? Commented Sep 8, 2017 at 17:41
  • Session::put('product', $product); - you're overwriting this every time, not appending it. If you want multiple products, then you'll have to store it as an array within the session. Commented Sep 8, 2017 at 17:43
  • 1
    @RobertRocha it's better to use an abstraction so he can swap implementations. If he were to use $_SESSION hard-coded like that it'd be a pain to change it all across the app. Commented Sep 8, 2017 at 17:54

2 Answers 2

4

You will have to use push here.

Session::push('product', $product);

So all new $product push into 'product' session variable.

Sign up to request clarification or add additional context in comments.

2 Comments

How do i print that array? means the session array?
$products = Session::get('product'); and you can run a foreach as $products is an array.
0

Use push to add a value to an array

public function postEnquote(Request $request)
{
   $product = Product::where('id',$request->Input(['product_id']))->first();
   Session::push('product', $product);
}

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.