Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

429
Vistas
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

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

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')
}
over 4 years ago · Santiago Trujillo Denunciar

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;

}
over 4 years ago · Santiago Trujillo Denunciar

0

Try it without the "first" method.

$companyName = $user->company()->name;
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda