Reputation: 1412
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
Upvotes: 3
Views: 6489
Reputation:
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');
If you're reading this and using laravel ^5.3.*
then the answer would be:
$company->employees()->pluck('id');
This would return a collection with all id's, if you want it to be an array you can chain the ->toArray()
behind it.
Upvotes: 3