【问题标题】:Laravel - Call to a member function save() on stringLaravel - 在字符串上调用成员函数 save()
【发布时间】:2020-03-01 07:38:36
【问题描述】:

我无法将会话中的项目数组保存到 mysql 数据库,但出现错误:

"Symfony \ Component \ Debug \ Exception \ FatalThrowableError (E_ERROR) Call to a member function save() on string"

当我执行 dd(Dump and Die) 时,数组显示如下:

    "{"1":{"name":"Bajiya","quantity":4,"price":"34.00"},
    "2":{"name":"Gulha","quantity":2,"price":"3.00"},
    "3":{"name":"kavaabu","quantity":1,"price":"2.00"}}"

以下是控制器存储功能:

public function storeCart(Request $request){

    $cart = new Cart;
    $cart= session()->get('cart');
    $cart =  json_encode($cart);
    $cart->save();
}

我的数据库中有一个表,其中包含 id 和 cart 列。我希望将上面的数组保存在购物车列中。

谢谢

【问题讨论】:

    标签: arrays json laravel-5 save


    【解决方案1】:

    每次覆盖之前的变量$cart

    $cart = new Cart; //put into $cart instance of Cart class
    $cart = session()->get('cart'); // overwrite other data to variable $cart
    $cart = json_encode($cart); // json_encode converts object/array to json (so at this moment you overwrite string to variable `$cart`
    $cart->save(); //you're trying to call function on json)))
    

    请试着理解,你到底想做什么))

    【讨论】:

      【解决方案2】:

      用一个简单的术语来解释我的解释,您需要指向数据库中将保留记录的列。代码如下所示

      $cart = new Cart;
      $cart->name= session()->get('name');
      $cart->quantity =  session()->get('quantity');
      $cart->price =  session()->get('price');
      $cart->save();
      

      由于您要保存一组项目,因此您可能希望使用 foreach,代码将变为如下所示:

      foreach ($cart as $item){
        $item->name= session()->get('name');
        $item->quantity =  session()->get('quantity');
        $item->price =  session()->get('price');
        $item->save();
      }
      

      您可能还想考虑使用关系。希望这有意义并有所帮助。

      【讨论】:

        【解决方案3】:

        使用下面的函数。

        public function storeCart(Request $request){
        
            $cart = new Cart();
            $cart->cart = $request->session()->get('cart');
            $cart->save();
            $request->session()->forget('cart');
            return redirect()->route('/');
        }
        

        【讨论】:

          猜你喜欢
          • 2016-06-29
          • 2017-05-22
          • 2021-07-20
          • 1970-01-01
          • 1970-01-01
          • 2020-01-08
          • 2018-09-03
          • 2021-12-10
          • 1970-01-01
          相关资源
          最近更新 更多