Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

archiebango's avatar

Eloquent Relationship: Inverse Question

Hi, I have 2 tables employers and employers_jobs. employers have a column of id and name while employers_jobs have a column of id employer_id and employers_job_title

the problem: the employers table returns null. I believe this called inverse relationship

here are some of my codes:

//Employer.php (model)
 public function EmployersJobs(){

        return $this->hasMany(EmployersJobs::class);
    }
//EmployersJobs.php (model) this might be the culprit
public function Employer(){

        return $this->belongsTo(Employer::class);
    }
//php artisan tinker, returns null
>>> App\EmployersJobs::find(1)->Employer;
=> null
//php artisan tinker
>>> App\Employer::find(1)->EmployersJobs;
//this is working
0 likes
3 replies
RamjithAp's avatar
Level 10

You need to pass your foreign key as the second parameter if the foreign key name is not exactly as "yourtablename_id"

//Employer.php (model)
 public function EmployersJobs(){

        return $this->hasMany(EmployersJobs::class,'employer_id');
    }
//EmployersJobs.php (model) this might be the culprit
public function Employer(){

        return $this->belongsTo(Employer::class,'id');
    }
1 like
archiebango's avatar

Hi @RamjithAp

Thank you very much, it's working :)

I edit some here and I didnt now there's foreign key exist.

return $this->belongsTo(Employer::class,'id');

Please or to participate in this conversation.