Search code examples
phprelationshipslaravel-5.6

Laravel relationship not working but foreign key has a value


I have a user model, in the model I have an integer field called role_id. if I echo out that value {{ $user->role_id }} I get a number back, I also have a relationship setup on the user model to the role model, but if I try and do {{ $user->role()->role_name }} I get the below error:

Undefined property: Illuminate\Database\Eloquent\Relations\HasOne::$role_name 

If I use the code {!! \App\Models\Role::whereKey($user->role_id)->pluck('role_name') !!} I get the value correctly, so it has to do with the relationship I just can't see where it is.

User Model

public function role()
{
    return $this->hasOne('\App\Models\Role');
}

Role Model

class Role extends Model

{ use SoftDeletes;

public $table = 'roles';

const CREATED_AT = null;
const UPDATED_AT = null;


protected $dates = ['deleted_at'];


public $fillable = [
    'role_name'
];

/**
 * The attributes that should be casted to native types.
 *
 * @var array
 */
protected $casts = [
    'id' => 'integer',
    'role_name' => 'string'
];

/**
 * Validation rules
 *
 * @var array
 */
public static $rules = [

];

public function users(){
    return $this->belongsTo('App\Models\User');
}

Solution

  • You should use magic property $role instead of relationship defining method role(). Try this:

    {{ $user->role->role_name }}