omrakhur omrakhur - 1 month ago 31
MySQL Question

Laravel relationship error: Undefined property: Illuminate\Database\Eloquent\Collection::$id on line 1

I have two models

Company
and
Employee
, with corresponding tables in MySQL,
companies
, and
employees
.

I have these Many-to-One relationships defined:

In the
Company
model:

public function employees(){
return $this->hasMany('App\Employee','company');
}


In the
Employee
model:

public function company(){
return $this->belongsTo('App\Company','company');
}


company
above in the methods is an unsigned integer foreign key present in the
employees
table.

In tinker I have tried
$company->employees;
, which returns a list of all the employees in the selected company. However, when I do
$company->employees->id
to get the IDs of all the employees only and not the other rows, it gives me the error:

PHP error: Undefined property: Illuminate\Database\Eloquent\Collection::$id on line 1

Answer

Well $company->employees returns a collection, ->id is not a property in the collection, thats why you get the error.

If you want to retrieve an array containing all the id's of your employees you might do this:

$company->employees()->lists('id');