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);

}

然后像这样在视图中检索它.

{{Session::get('cart')}}

然而,我总是遇到这样的错误.

htmlentities() expects parameter 1 to be string, array given

有关如何创建存储一系列商品的购物车的任何线索和建议.

推荐答案

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);

这将使它的工作时,你将使用{{Session::get('cart');}}在你的htmls.请注意Session::push,因为它总是会在会话中附加新产品.你应该使用Session::put来确保产品总是在更新.

Laravel相关问答推荐

Laravel中的HTTP请求如何工作?

Inertia React中的错误文件上传更新

灯丝:设定模式标题

哈希:check()不返回预期结果Laravel 10

在 React 中将属性从一个组件传递到另一个组件

如何更改 laravel sanctum 返回message: Unauthenticated.

如何在 Laravel Passport 中获取刷新令牌?

Laravel 5 Eloquent 范围连接并 Select 特定列

Laravel 4:如何将 WHERE 条件应用于 Eloquent 类的所有查询?

Laravel 4:验证前修剪输入的最佳实践

会话中的 Laravel 存储数组

Laravel Nova - 重新排序左侧导航菜单项

Web 服务器如何处理请求?

当表中不存在列时如何将 paginate() 与 having() 子句一起使用

Laravel 验证 pdf mime

Laravel 5.3 通知 - 仅使用Electron邮件地址通知

Laravel 如何从子域 URL 中删除api前缀

Carbon解析到 ISO8601

Laravel 用户能力

Eloquent的关系 - attach附加(但不保存)到 Has Many