Eloquent Laravel show Trying to get property 'code' of non-object

Viewed 2234

I have 2 model created like below:

Employee.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    public function grades(){
        return $this->belongsTo(Grade::class);
    }
}

and also

Grade.php

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;

class Grade extends Model
{
    public function employee(){
        return $this->hasMany(Employee::class);
    }
}

when I try to show code ane name of Grade in tinker like below

$a=App\Employee::find(15);<br>
$a->grades->code

it gives me error :

PHP Notice: Trying to get property 'code' of non-object in Psy Shell code on line 1*

table employees:

employees

table grades:

grades

2 Answers

Change your grades() method in the Employee model to grade().

Eloquent uses the method name to determine the database column to use for the relationship. It would have also worked if you changed the column name to grades_id or if you optionally defined the column on the relationship like this:

public function grades() 
{
    return $this->belongsTo(Grade::class, 'grade_id');
}

Please add with and try :

$a = App\Employee::with('grades')->find(15);
Related