Laravel 在会话中存储数组

Laravel Store Array in Session(Laravel 在会话中存储数组)
本文介绍了Laravel 在会话中存储数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我在会话中存储数组时遇到问题.我正在制作购物车,但它似乎不起作用.

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 在会话中存储数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

In PHP how can you clear a WSDL cache?(在 PHP 中如何清除 WSDL 缓存?)
failed to open stream: HTTP wrapper does not support writeable connections(无法打开流:HTTP 包装器不支持可写连接)
Stop caching for PHP 5.5.3 in MAMP(在 MAMP 中停止缓存 PHP 5.5.3)
Caching HTTP responses when they are dynamically created by PHP(缓存由 PHP 动态创建的 HTTP 响应)
Memcached vs APC which one should I choose?(Memcached 与 APC 我应该选择哪一个?)
What is causing quot;Unable to allocate memory for poolquot; in PHP?(是什么导致“无法为池分配内存?在 PHP 中?)