使用 cURL 获取响应更新 Laravel 数据库 table

Update Laravel Database table with cURL Get Response

我正在尝试执行 cURL GET 请求并使用响应来更新我的 table,但出现以下错误:

类型错误 Illuminate\Database\Eloquent\Builder::create():参数 #1 ($attributes) 必须是数组类型,字符串给定,在第 23 行 /home/vagrant/code/bp/vendor/laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php 中调用

一个类似的通过Postman的GET请求returns响应结构如下:

{
    "results": [
        {
            "transaction": "List",
            "records": [
                {
                    "CONO": "100",
                    "LNCD": "EN",
                    "CUNO": "000040",
                    "CUNM": "Custonmer Name",
                    "CUA1": "1234 Test Road",
                    "CUA2": "Alaska",
                    "CUA3": "USA",
                    "CUA4": "Test",
                   
                },

控制器:M3customCrudController.php

class M3ImportController extends CrudController {

public function fetchcust() {

             
    $url = "https://abc123.com";
    

    //will be as an admin field in official version
    $username = 'xxx';
    $password = 'yyy';

    //Curl
    $curl = curl_init($url);

    curl_setopt($curl, CURLOPT_HEADER, FALSE);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
    curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_USERAGENT, 'SP connector');
    curl_setopt($curl, CURLOPT_USERPWD, $username . ":" . $password);
  
    $response = curl_exec($curl);    
    $info = curl_getinfo($curl);

    $response = [
    'headers' => substr($response, 0, $info["header_size"]),
    'body' => substr($response, $info["header_size"]),
    ];

   $mydata = $response['body'];
    
    M3custom::create($mydata);

    }

}

首先 - 使用 Http facade,而不是 curl。

其次 - 您得到 json(字符串)而不是将其转换为数组。

第三 - 您的模型结构与响应相同?我不这么认为。

代码可能是这样的,但可能需要转换以适应模型的结构

public function fetchcust() {
    $url = "https://abc123.com";
    //will be as an admin field in official version
    $username = 'xxx';
    $password = 'yyy';
    $response = Http::withBasicAuth($username, $password)
        ->withUserAgent('SP connector')
        ->get($url)
        ->json('results.records');
    M3custom::create($response);
}