0

In my laravel 4.2 application, i want to store the cart item details in session.

cartId =>[
            0 => [
                productId => x,
                quantity  => y
            ],
            1 => [
                productId => u,
                quantity  => v
            ],
            2 => [
                productId => l,
                quantity  => m
            ]

         ]

I didn't found a way except this

Session::push('user.teams', 'developers');

for storing as array in session. but the same is not applicable here

2
  • 1
    Try: Session::put(<key>, json_encode($your_array)); Commented May 17, 2018 at 10:05
  • Yeah,Session::put($shoppingCartId, json_encode($array)); $test = Session::get($shoppingCartId); $test1 = json_decode($test); dd($test1[0]->productId); solved to an extend Commented May 17, 2018 at 11:39

2 Answers 2

1

Looks like you can insert the array directly in the session.

$someArray = ['name' => 'John Doe', 'username' => 'jdoe'];

Session::put('user', $someArray);

When you want to retrieve its value just need to:

$user = Session::get('user');
echo $user['name'] // output: John Doe

Same applicable for multidimensional array...

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

Comments

1

You can just store the information in the key required, such as:

$cartDetails = [ 
                 0 => [
                       productId => x,
                       quantity  => y
                 ],
                 1 => [
                       productId => u,
                       quantity  => v
                 ],
                 2 => [
                       productId => l,
                       quantity  => m
                 ]
               ];

Session::put('cart', $cartDetails);

Each user will have it's own cart, can you can validate with Session::has('cart') and Session::get('cart') will get you the content of $cartDetails.

Session::forget('cart') will erase the key 'cart' from the Session, meaning Session::has('cart') == false and Session::get('cart') is null

If you plan on using key's as Id's (Something among the lines of Session::put($cartId, $cartDetails)), I wouldn't advise as later on, if you need to add something with the same logic, you will compromise the Session's key and possibly, overwrite it. Same applies if someone else takes a look at the code (or even you in a not-so-long future) and need to read the code, there isn't a clear perception of whats in the session unless you read the whole function. (IMO)

https://laravel.com/docs/4.2/session

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.