如何防止未定义属性:按下API时stdClass :: $ data

时间:2018-10-09 07:18:04

标签: php laravel api

我已经使用Laravel创建了一个表单,借此从用户那里获取应该存储在API中的数据。我编写了一个单独的名为 global_curl 的函数,该函数应该将数据发布到API。问题是,当我尝试通过发布请求访问REST API时,出现以下错误:(1 / 1)ErrorException 未定义的属性:stdClass :: $ data

我的控制器

//Post Request of plan entries
public function validatePlanEntries(Request $request){
    $data = array(
        'DobPrincipalTraveller' => $request->dob,
        'TravelStartDate' => $request->departure_date,
        'TravelEndDate' => $request->return_date,
        'CoverOption' => $request->cover,
        'DobOfSpouse' => $request->spousedob,
        'Children' => '2018-10-07',
        'WithSpouse' => 0
    );
    // dd($data);
   /*Posts data to Travel Plans API*/
   $travelplan_data = $this->global_Curl($data, 'api/travel/get-plans')->data;
}

卷曲功能

public function global_Curl($data, $url){
    //dd($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url));
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($ch));
    curl_close($ch);
    return $response;
}

POSTMAN的API数据结构

{
    "DobPrincipalTraveller":"1978-01-22",
    "TravelStartDate":"2018-10-20",
    "TravelEndDate":"2018-10-25",
    "CoverOption":"Standard",
    "WithSpouse":"1",
    "DobOfSpouse":"1985-03-18",
    "Children":[
        {
            "DateOfBirth":"2015-05-23"
        },
        {
            "DateOfBirth":"2016-09-13"
        }
    ]
}

2 个答案:

答案 0 :(得分:0)

应该是这样。

$travelplan_data = $this->global_Curl($data, 'api/travel/get-plans');

答案 1 :(得分:0)

应该是这样的: 当您将数组传递给函数时,它应该能够接受数组作为参数,因此您应该像我一样定义curl函数。

//Post Request of plan entries
public function validatePlanEntries(Request $request){
    $data = array(
        'DobPrincipalTraveller' => $request->dob,
        'TravelStartDate' => $request->departure_date,
        'TravelEndDate' => $request->return_date,
        'CoverOption' => $request->cover,
        'DobOfSpouse' => $request->spousedob,
        'Children' => '2018-10-07',
        'WithSpouse' => 0
    );
    // dd($data);
   /*Posts data to Travel Plans API*/
   $travelplan_data = $this->global_Curl($data, 'api/travel/get-plans');
}

public function global_Curl(array $data, $url){
    //dd($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, ($_ENV['API_ENDPOINT_NGINX_IP'] . '/' . $url));
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $response = json_decode(curl_exec($ch));
    curl_close($ch);
    return $response;
}

尝试一下。 希望它能工作