class User extends Authenticatable
{
public function company() {
return $this->belongsTo('App\Company');
}
}
class Company extends Model
{
public function users() {
return $this->hasMany('App\User');
}
}
id name companies_id
id name
I'm trying to get the name of the company attached to the user.
$user = User::findOrFail(Auth::user()->id);
$companyName = $user->company()->first()->name;
I got this error message Trying to get property of non-object
I don't get what I'm missing... Thank you in advance
By default, Eloquent is taking the name of the relationship + '_id' to guess the foreign key.
public function company() {
return $this->belongsTo('App\Company', 'companies_id')
}
public function companies() {
return $this->belongsTo('App\Company')
}
Also it may be null your company_id field
That reason you must be check your field on the loop
f.e
foreach($users as $user)
{
if(isset($user->company->title)):
echo $user->company->title;
else:
echo 'empty';
endif;
}
Try it without the "first" method.
$companyName = $user->company()->name;