Search code examples
laraveleloquentormeloquent-relationshiplaravel-relations

Not able to fetch data from multiple hasMany relations - laravel


I wanted to fetch whole data from all 4 relations: education,documents,references,skills along with the User table's data. The following query only returns data from user table but not from any of the 4 relations although they have matching data in them. I have added its screenshot at the bottom. Can someone tell me how to fix this?

Controller

$u = User::where('id', $id)->with(['education','documents','references','skills'])->get();
dd($u);

User Model

public function education(){
    return $this->hasMany(StaffEducation::class,'id','user_id');
}
public function documents(){
    return $this->hasMany(StaffDocuments::class,'id','user_id');
}
public function references(){
    return $this->hasMany(StaffReferences::class,'id','user_id');
}
public function skills(){
    return $this->hasMany(StaffSkills::class,'id','user_id');
}

enter image description here


Solution

  • This is the right way

    return $this->hasMany(StaffEducation::class, 'foreign_key', 'local_key');

    public function education(){
        return $this->hasMany(StaffEducation::class,'user_id','id');
    }
    

    Use the same for the rest of your relations