Laravel belongs to relationships - attempt to get property of not object

User.php

class User extends Authenticatable
{
    public function company() {
        return $this->belongsTo('App\Company');
    }
}

Company.php

class Company extends Model
{
    public function users() {
        return $this->hasMany('App\User');
    }
}

Table users

id name company_id

Company table

id name

I am 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 do not understand what I am missing ... Thanks in advance

+4
source share
3 answers

By default, Eloquent takes the relationship name + '_id' to guess the foreign key.

Solution A

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

Solution B

public function companies() {
    return $this->belongsTo('App\Company')
}
+2
source

Try it without the "first" method.

$companyName = $user->company()->name;
0
source

company_id

f.e

foreach($users as $user) 
{
   if(isset($user->company->title)): 

     echo  $user->company->title;
   else:

     echo 'empty';
   endif;

}
0

Source: https://habr.com/ru/post/1674242/


All Articles