简体   繁体   English

更新 Laravel 6 中的会话数组值

[英]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我在 Laravel 中有一个包含数组值的会话,我想在页面刷新时编辑一个数组成员

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.Session 获取它,更改您的数组,然后使用新数据从控制器重新保存它。

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. IE 如果用户已添加到购物车并单击提交,那么它将通过您的控制器进行更新并保存到Session如上所述。 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.如果他们将商品添加到购物车并点击刷新,您可能不希望data值发生变化,因为他们只是点击了刷新,但并未提交要添加到购物车的值。 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希望这可以帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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