简体   繁体   中英

update session array value in laravel 6

i have a session with array value in laravel and i want to edit one array member when page is refresh

my session like this

            $data = [
            'product' => $request->input('product'),
            'price' => $request->input('price'),
            'quantity' => 1
            ];

            $request->session()->put('cart_'. $request->input('id') , $data);

and i want to plus price value when page refreshed

like this

before page refresh

//session like this

[
'product' => 'test 1',
'price' => 300,
'quantity' => 1
]


after page refreshed

//session like this

[
'product' => 'test 1',
'price' => 600,
'quantity' => 2
]


new value save in the same session and when page refresh again , session value plus new price and quantity

Sure, you can do this like a normal variable. Grab it from Session , change your array, and then resave it from your controller with the new data.

So in your Controller :

$data= Session::get('data', []);  // Empty array if hasn't been set / nothing in cart

// Here you would have your business logic, this is just static to demonstrate
$data = [
          'product' => 'test 1',
          'price' => 600,
          'quantity' => 2
];

Session::set('data', $data);

You've asked on a refresh. The refresh of the page should not change the data. IE if the user has added to the cart and clicked submit , then it will have gone through your controller to be updated and saved to Session as above. If they add items to the cart, and hit refresh, you likely wouldn't want the data values to change, as they have just hit refresh, but not submitted the values to be added to the cart. So, once the cart is legitimately updated (gone through controller), that session data is stored. So on each refresh, your page (or controller) can pull from that session data from

Session::get('data', [])

Hope this helps

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