Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

428
Views
Laravel belongsTo relationship - Trying to get property of non-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 companies_id

Table companies

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

about 4 years ago · Santiago Trujillo
3 answers
Answer question

0

By default, Eloquent is taking the name of the relationship + '_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')
}
about 4 years ago · Santiago Trujillo Report

0

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;

}
about 4 years ago · Santiago Trujillo Report

0

Try it without the "first" method.

$companyName = $user->company()->name;
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!