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

garrettmassey's avatar

HasManyThrough relationship returning empty array

Hello!

I have a database that has several tables, but we only need to focus on 3:

providers

  • id
  • name
  • status
  • type_of_care_id

caretype

  • id
  • name
  • category

category

  • id
  • name

A provider can have 1 care type, and multiple care types can belong to 1 category.

I have a HasManyThrough relationship set up in my CareCategory controller, but it returns an empty array, and I'm not quite sure why:

class CareType extends Model
{
    public function providers() {
        return $this->hasMany('App\Models\Providers', 'type_of_care_id');
    }

    public function category() {
        return $this->belongsTo('App\Models\CareCategory', 'category');
    }
}


class CareCategory extends Model
{
    public function care_type() {
        return $this->hasMany('App\Models\CareType', 'category');
    }

    public function providers()
    {
        return $this->hasManyThrough('App\Models\Provider', 'App\Models\CareType', 'category', 'type_of_care_id', 'id', 'id');
    }
}


class Provider extends Model
{
    public function caretype() {
        return $this->belongsTo('App\Models\CareType', 'type_of_care_id');
    }
}

When I try to get the providers in a specific category like this: $cat_pro = CareCategory::find($id)->providers(); it returns an empty array, even though I know there are providers in that category.

Any help would be greatly appreciated!

0 likes
5 replies
frankielee's avatar

Missing get() ?

$cat_pro = CareCategory::find($id)->providers()->get();
garrettmassey's avatar

Sorry for the late reply,

when I add ->get() it still returns an empty set / collection.

garrettmassey's avatar

Unfortunately all configurations of the foreign key orders either returns a foreign-key-constraint error or it "works" but the array is still empty, or the count is still 0.

I'm stumped so far.

garrettmassey's avatar
garrettmassey
OP
Best Answer
Level 6

So, I realized after migrating my code to a new repository, I didn't run the database migrations. The code was actually working, but because I hadn't run the migrations there wasn't any data to show, hence the empty array and 0 count. Running the migrations worked, and I completely forgot to check that when I moved to the new repository.

Thank you for your help!

Please or to participate in this conversation.