Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

noblemfd's avatar

ErrorException : Trying to get property 'staff_id' of non-object

In my Laravel-5.8, I have this 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",
  },
]

Which I tried to consume and save using Guzzle

namespace App\Console\Commands; use 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(),
        ]);               
    }           
}

when I ran php artisan, I got this error:

ErrorException : Trying to get property 'staff_id' of non-object

How do I resolve it?

Thanks

0 likes
3 replies
MichalOravec's avatar

I think it should be like this

$clientdatas = json_decode($res);

instead of

$clientdatas = json_decode($res->getContents(), true);       
guybrush_threepwood's avatar
Level 33

When you call json_decode() you're specifying that you want the contents as an associative array:

json_decode($res, true); 

So either access the properties as an array:

        Employee::updateOrCreate([
            'employee_code' => $clientdata['staff_id'],
        ],
        [
            'first_name'                => $clientdata['first_name'],
            'last_name'                 => $clientdata['last_name'],
            'date_of_birth'             => Carbon::parse($clientdata['date_of_birth'])->toDateString(),
        ]);     

Or modify the call to be:

json_decode($res); 

And access the properties of the object (you need to update the date_of_birth reference and fix the last_name property name on your existing code):

        Employee::updateOrCreate([
            'employee_code' => $clientdata->staff_id,
        ],
        [
            'first_name'                => $clientdata->first_name,
            'last_name'                 => $clientdata->last_name,
            'date_of_birth'             => Carbon::parse($clientdata->date_of_birth)->toDateString(),
        ]);      

Please or to participate in this conversation.