問題描述
我在會話中存儲數組時遇到問題.我正在制作購物車,但它似乎不起作用.
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 在會話中存儲數組的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!