Q:

How to display Model Relationship in Laravel?

I have this database table: job, department, pcn and this table pcn has properties job_id and department_id on it. So in Laravel I have this definitions on its equivalent models:
class Job extends Model
{
    public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}

class Department extends Model
{
    public function pcns(){return $this->hasMany('App\Pcn', 'id');}
}

class Pcn extends Model
{
    public function job(){return $this->belongsTo('App\Job');}

    public function department(){return $this->belongsTo('App\Department');}
}

My problem now is my pcn index that displays list of Pcn is giving me this error:
Trying to get property 'name' of non-object (View: C:\wamp\www\bookersystem\resources\views\pcn\index.blade.php)

in which my index.blade.php has this:
@foreach($pcns as $key => $value)
    <td>{{ $value->control_number }}</td>
    <td>{{ $value->job->name }}</td>
    <td>{{ $value->department->name }}</td>
@endforeach

On my Pcn controller:
public function index()
{

    $pcns = Pcn::paginate(50);

    return view('pcn.index', compact('pcns'));

}

As for my migrations i have this difinition:
public function up()
{
    Schema::create('pcn', function (Blueprint $table) {
        $table->engine = "InnoDB";
        $table->charset = 'utf8mb4';
        $table->collation = 'utf8mb4_general_ci';
        $table->bigIncrements('id');
        $table->unsignedBigInteger('department_id');
        //$table->foreign('department_id')->references('id')->on('department');
        $table->unsignedBigInteger('job_id');
        //$table->foreign('job_id')->references('id')->on('job');
        $table->string('control_number', 45);
        $table->string('center', 5);
        $table->string('status', 8)->nullable();
        $table->unsignedBigInteger('mrf_id')->nullable();
        $table->string('degree', 25)->default('Not Recruiting');
        $table->timestamps();
    });
}

Am i doing wrong here?

A:

Firt thing it's better to remove the id from the relationships definition or declare the right foreign key:
class Job extends Model
{
    //this
    public function pcns(){return $this->hasMany('App\Pcn');}
    //or this
    public function pcns(){return $this->hasMany('App\Pcn', 'job_id', 'id');}
}

class Department extends Model
{
    //this
    public function pcns(){return $this->hasMany('App\Pcn');}
    //or this 
    public function pcns(){return $this->hasMany('App\Pcn', 'department_id', 'id');}
}

Second step: it's better to eager load the relationships to reduce the number of queries needed:
public function index()
{
    $pcns = Pcn::with(['job', 'department'])->paginate(50);

    return view('pcn.index', compact('pcns'));
}

After that in your view you don't really need $key=>$value in the @foreach:
@foreach($pcns as $pcn)
    <td>{{ $pcn->control_number }}</td>
    <td>{{ $pcn->job->name }}</td>
    <td>{{ $pcn->department->name }}</td>
@endforeach

