Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

427
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

Try it without the "first" method.

$companyName = $user->company()->name;
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda