简体   繁体   English

laravel 返回数组到字符串转换错误

[英]laravel return array to string conversion error

I have store method in my controller and it returns this errors:我的 controller 中有存储方法,它返回此错误:

Errors错误

Console Preview tab控制台Preview tab

exception: "ErrorException"
file: "C:\........\vendor\laravel\framework\src\Illuminate\Support\Str.php"
line: 419
message: "Array to string conversion"

Console Response tab控制台Response tab

   {
        "file": "C:\\........\\app\\Http\\Controllers\\Api\\Front\\CartController.php",
        "line": 380,
        "function": "save",
        "class": "Illuminate\\Database\\Eloquent\\Model",
        "type": "->"
    },

Code代码

public function checkout(Request $request)
{
    $user = auth('api')->user();
    $cartItems = CartStorage::where('user_id', $user->id)->get();
    $address = AddressUser::where('id', $request->input('address'))->first();

    foreach($cartItems as $item) {
        $cartData = $item->cart_data;
        // add to orders table
        try {
            $order = new Order();
            $order->ordernu = 'Si-'.mt_rand(1000000000, 9999999999);
            $order->user_id = $user->id;
            $order->order_data = $cartData;
            $order->quantity = $cartData['quantity'];
            $order->price = $request->input('totalPrice');
            $order->courier = $request->input('courier');
            $order->courier_service = $request->input('courierService');
            $order->shippingcode = $request->input('shippingcode');
            $order->shipping_price = $request->input('shippingPrice');
            $order->address = $address->address;
            $order->kecamatan = $address->kecamatan;
            $order->kelurahan = $address->kelurahan;
            $order->kota = $address->kota;
            $order->provinsi = $address->provinsi;
            $order->postalcode = $address->postalcode;
            $order->weight = $request->input('weight');
            $order->phone = $request->input('phone');
            $order->buyer_name = $user->name;
            $order->buyer_email = $user->email;
            $order->note = $request->input('note');
            $order->received = false;
            $order->save();

            // reduce stock of each product
            foreach ($cartItems as $item) {
                $cartData = $item->cart_data;
                $product = Product::find($cartData['productId']);
                $product->decrement('qty', $cartData['quantity']);
            }

        } catch (Exception $e) {
            return response($e->getMessage(), 400);
        }
    }
}

Note: I've tested dd every single data that I placed in order column and all are getting true values.注意:我已经测试了dd我放置在order列中的每一个数据,并且所有数据都得到了真实值。

Any idea?任何想法?

I think the problem is here:我认为问题出在这里:

$order->order_data = $cartData; $order->order_data = $cartData;

$cartData is an array and cannot be saved into database directly. $cartData是一个数组,不能直接存入数据库。

That's why you got Array to string conversion error.这就是为什么你得到数组到字符串转换错误的原因。

this because you try to store array as a string into the database, to store array into the database you have either:这是因为您尝试将数组作为字符串存储到数据库中,将数组存储到您拥有的数据库中:

  1. $data_to_store=json_encode($array) then when callback $array=json_decode($db_data) $data_to_store=json_encode($array)然后当回调$array=json_decode($db_data)
  2. $data_to_store=serialize($array) then when callback $array=unserialize($db_data) $data_to_store=serialize($array)然后当回调$array=unserialize($db_data)
  3. $data_to_store= implode(',!', $array) then when callback $array = explode(',!', $db_data) $data_to_store= implode(',!', $array)然后当回调$array = explode(',!', $db_data)

check also this amazing answer还要检查这个惊人的答案

I was seeking for the same solution and this worked for me.我正在寻找相同的解决方案,这对我有用。 Assuming your order_data column on the Order model is of type json.假设 Order model 上的order_data列的类型为 json。 Define the casts property in your Order model with order_data as an array.Order model 中定义 casts 属性,其中order_data作为数组。 You won't need json_encode if you use it this way as laravel will convert the array into json for you.如果您以这种方式使用它,则不需要 json_encode,因为 laravel 将为您将数组转换为 json。

class Order extends Model
{
    protected $casts = [
        'order_data' => 'array'
    ];
}

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

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