简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM