【问题标题】:Laravel Store Array in Session会话中的 Laravel 存储数组
【发布时间】:2016-09-17 05:41:30
【问题描述】:

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

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

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

【问题讨论】:

    标签: php laravel laravel-5.2


    【解决方案1】:

    您在会话中存储了一个数组,由于{{ }} 需要一个字符串,因此您不能使用{{Session::get('cart')}} 来显示该值。

    {{ $var }} 与写echo htmlentities($var) 相同(一个非常简单的例子)。

    相反,您可以执行以下操作:

    @foreach (Session::get('cart') as $product_id)
        {{$product_id}}
    @endforeach
    

    【讨论】:

    • 我很好奇为什么集合或 $request->all() 可以通过 {{ }} 使用? htmlentities 不也通过它们吗?
    • @Nello Collections 提供了一个用于处理数组的包装器。如果您尝试echo $collection 或使用{{ $collection }},Collection 会使用__toString() 方法自动处理此问题。 $request->all() 将作为集合处理,而不是普通数组。
    【解决方案2】:

    如果你需要使用 session 中的数组作为字符串,你需要像这样使用 Collection:

    $product = collect([1,2,3,4]);
    Session::push('cart', $product);
    

    当您在 html 中使用 {{Session::get('cart');}} 时,这将使其工作。请注意Session::push,因为它将始终在会话中附加新产品。您应该使用Session::put 以确保产品始终在更新。

    【讨论】:

      【解决方案3】:

      如果你使用'push',当最初在会话中创建数组时,数组将如下所示:

      [
          0 => [1,2,3,4]
      ]
      

      你应该使用'put':

      $products = [1,2,3,4];
      $request->session()->put('cart', $products);
      

      任何后续值都应该被推送到会话数组中:

      $request->session()->push('cart', 5);
      

      【讨论】:

      • 完全正确,感谢您的发现。我已经更正了代码。
      【解决方案4】:

      您可以在会话中声明一个数组,例如 $cart = session('data', []);

      $cart[] = $product;
      
      session([ 'data' => $cart]);
      
      return session('data', []);
      

      【讨论】:

        【解决方案5】:

        你可以使用.:

        $product = array(1,2,3,4);
        Session::put('cart.product',$product);
        

        【讨论】:

          【解决方案6】:

          你也可以这样做:

            $data = collect($Array); 
            Session()->put('data', $data);
            return view('pagename');
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2019-05-02
            • 2015-05-22
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多