I simply cannot wrap my head around Models.
I have two tables, users
and companies
. Users contains a column called Company
which is a foreign key to the companies
table. the companies table has two columns, an ID
and company_name
The value of Company
under users
references the id in Companies
.
I am trying to get the value of company_name through the foreign key like so.
$user = User::find(1)->company->company_name;
My thought process, which may be wrong, is that this (depending on if models are correct) should get the value of the Company column and then using that value, get the company_name from the Companies table.
My models look like so
User
public function company() {
return $this->belongsTo('App\Company', 'company');
}
Company
protected $table = 'companies';
public function user() {
return $this->hasOne('App\User');
}
All I continuously get is Trying to get property of non-object
I can see in the error log it gives that it's actually getting the company name too!
Trying to get property of non-object', 'C:\wamp\www\laravel\app\Http\Controllers\HomeController.php', '41', array('userid' => '1', 'usercompany' => '1', 'company' => 'BMW'))
But I don't understand where it's pullyig userid
and usercompany
from.
What am I doing wrong?