简体   繁体   中英

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:

"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:

    "{"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:

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. I want the array above to be saved in the cart column.

Thanks

Each time you override previous variable $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.

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 ($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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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