【问题标题】:Laravel - ErrorException : Trying to get property 'staff_id' of non-objectLaravel - ErrorException:试图获取非对象的属性'staff_id'
【发布时间】:2020-09-30 11:59:35
【问题描述】:

在我的 Laravel-5.8 中,我有这个 API:

[
  {
    "date_of_birth": "2009-11-21T00:00:00",
    "first_name": "JAGUA",
    "last_name": "KING",
    "staff_id": "44444",
  },
  {
    "date_of_birth": "2005-11-21T00:00:00",
    "first_name": "JACKIE",
    "last_name": "LEE",
    "staff_id": "44444",
  },
]

我尝试使用 Guzzle 消费和保存

命名空间应用\控制台\命令; 使用 Illuminate\Console\Command;

public function handle()
{       
    $client = new Client();
    $res = $client->request('GET','https://api.employees.net/allemployees', [
     'query' => ['key' => 'dfffgggggffffff']
   ])->getBody();

    $clientdatas = json_decode($res->getContents(), true);        

    foreach($clientdatas as $clientdata)
    {         
        Employee::updateOrCreate([
            'employee_code' => $clientdata->staff_id,
        ],
        [
            'first_name'                => $clientdata->first_name,
            'last_name'                 => $clientdata->flast_name,
            'date_of_birth'             => Carbon::parse($clientdata['date_of_birth'])->toDateString(),
        ]);               
    }           
}

当我运行 php artisan 时,我得到了这个错误:

ErrorException : 试图获取非对象的属性“staff_id”

我该如何解决?

谢谢

【问题讨论】:

  • 尝试在结果中使用 dd() 函数(转储和死)来查看数据的路径是否符合您的预期

标签: laravel


【解决方案1】:

json_decode() 的第二个参数是它是否应该返回关联。您将其设置为 true,它将返回 array

当您将它用作对象时,这种方法是正确的。

$clientdatas = json_decode($res->getContents());

并更改要用作对象的数组访问权限。

$clientdata['date_of_birth']

应该是。

$clientdata->date_of_birth;

【讨论】:

    猜你喜欢
    • 2017-08-02
    • 2018-04-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 2016-11-30
    • 2017-02-25
    • 1970-01-01
    相关资源
    最近更新 更多