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

killstreet's avatar

Not sure what kind of eloquent query to make with inbetween table

So I got the following table structure:

  • profiles
  • id
  • name
  • lastname
  • profiles_has_specialties
  • profile_id
  • specialty_id
  • level
  • specialties
  • id
  • name

Now I thought I would need a query like:

//Inside the controller
dd(Profile::with('specialties'));

//The Profile model
public function specialties()
{
    return $this->hasManyThrough(Profile_has_specialty::class, Specialty::class, 'id', 'profiles_id');
}

But this returns nothing. The specialties remains empty. How would I achieve that I can get all specialties for a given user with Eloquent?

0 likes
4 replies
tykus's avatar

Looks like a belongsToMany relation is what you need.

//The Profile model
public function specialties()
{
    return $this->belongsToMany(Speciality::class)->withPivot('level');
}
killstreet's avatar

@tykus once I added your line it will instandly try to load a table that does not exists with the following error

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cv-matching.profile_specialty' doesn't exist (SQL: select `specialties`.*, `profile_specialty`.`profile_id` as `pivot_profile_id`, `profile_specialty`.`specialty_id` as `pivot_specialty_id` from `specialties` inner join `profile_specialty` on `specialties`.`id` = `profile_specialty`.`specialty_id` where `profile_specialty`.`profile_id` in (1))
tykus's avatar
tykus
Best Answer
Level 104

Ah, yes. I see you have a non-conventional pivot table name, so you need to specify this as the second argument:

//The Profile model
public function specialties()
{
    return $this->belongsToMany(Speciality::class, 'profiles_has_specialties')->withPivot('level');
}

Sorry I missed that the first time!

1 like
killstreet's avatar

@tykuy Thanks! I simply had to add the correct column, just as those arent in the typical conventional syntax so I had to update it to

return $this->belongsToMany(Specialty::class, 'profiles_has_specialties', 'profiles_id', 'specialties_id' )->withPivot('level');

many thanks! :)

Please or to participate in this conversation.