【问题标题】:Update Laravel Database table with cURL Get Response使用 cURL 获取响应更新 Laravel 数据库表
【发布时间】:2021-10-09 22:53:09
【问题描述】:

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

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

通过 Postman 的类似 GET 请求返回以下响应结构:

{
    "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);

    }

}

【问题讨论】:

    标签: php laravel curl laravel-backpack


    【解决方案1】:

    首先 - 使用 Http 外观,而不是 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);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 2016-11-18
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多