简体   繁体   English

Laravel - 在字符串上调用成员 function save()

[英]Laravel - Call to a member function save() on string

I am unable to save an array of items from session to mysql database with an error:我无法将一系列项目从 session 保存到 mysql 数据库,但出现错误:

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

When I do a dd(Dump and Die) the array is displayed as below:当我执行 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"}}"

Below is the controller store function:下面是controller商店function:

public function storeCart(Request $request){

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

I have a table in my Database with columns for id and cart.我的数据库中有一个表,其中包含 id 和 cart 列。 I want the array above to be saved in the cart column.我希望将上面的数组保存在购物车列中。

Thanks谢谢

Each time you override previous variable $cart每次覆盖之前的变量$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)))

Please try to understand, what exactly you want to do))请尝试了解您到底想做什么))

Works with the function below.适用于下面的 function。

public function storeCart(Request $request){

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

To put my explanation in a simple term, you need to point to the columns in the DB where the records will be persisted.用一个简单的术语来解释我的解释,您需要指向数据库中将保留记录的列。 The code could look like this below代码可能如下所示

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

Since you are saving an array of items you may want to use the foreach and the code will change to something like this:由于您要保存一组项目,因此您可能希望使用 foreach 并且代码将更改为如下所示:

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

You may also want to consider using relationships.您可能还需要考虑使用关系。 Hope this makes sense and helps.希望这有意义并有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM