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

All we need is an easy explanation of the problem, so here it is.

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

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

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.

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply