Geethu
Geethu

Reputation: 390

Laravel 4.2 : keep multidimensional array data in session

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

Upvotes: 0

Views: 1496

Answers (2)

Helder Lucas
Helder Lucas

Reputation: 3343

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

Upvotes: 1

abr
abr

Reputation: 2129

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

Upvotes: 1

Related Questions