Laravel在会话中存储数组 [英] Laravel Store Array in Session
问题描述
我在会话中存储数组时遇到了麻烦.我在做购物车,但似乎不起作用.
I have been having trouble storing an array in session. I am making a shopping cart and it doesn't seem to work.
public function __construct(){
$product = array(1,2,3,4);
Session::push('cart', $product);
}
,然后在这样的视图中检索它.
and then retrieve it in the view like this.
{{Session::get('cart')}}
但是我一直收到这样的错误.
However I keep getting an error like this.
htmlentities() expects parameter 1 to be string, array given
关于如何创建存储一系列商品的购物车的任何线索和建议.
Any clues and advice on how to create a shopping cart that stores an array of items.
推荐答案
如果您需要使用session中的数组作为字符串,则需要使用Collection,如下所示:
If you need to use the array from session as a string, you need to use Collection like this:
$product = collect([1,2,3,4]);
Session::push('cart', $product);
当您在html中使用{{Session::get('cart');}}
时,这将使其起作用.请注意Session::push
,因为它将始终在会话中附加新产品.您应该使用Session::put
来确保产品将始终处于更新状态.
This will make it work when you will be using {{Session::get('cart');}}
in your htmls. Be aware of Session::push
because it will append always the new products in sessions. You should be using Session::put
to be sure the products will be always updating.
这篇关于Laravel在会话中存储数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!