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

algae14's avatar

Eloquent query for great-grandchildren?

Ok, so I have the following model hierarchy:

  • Companies have Departments.
  • Departments have Employees.
  • Employees have Benefits.

So, Benefits are great-grandchilden of Companies.

At the place in my code where I'm stuck, I have a particular instance of the Company model. And, I know that I can do the following with Eloquent to retrieve a given Company's Employees:

public function index(Company $company)
{
$employees = $company->hasManyThrough('App\Employees', 'App\Departments');
}

But, what I actually need for the particular $company instance are that company's Benefits. The only way I know how to do this is by looping through the $employees collection as follows:

public function index(Company $company)
{
    $employees = $company
                ->hasManyThrough('App\Employees', 'App\Departments');

    foreach ($employees as $employee) 
    {

        $company_benefits = $employee->benefits;

    }
}

More specifically, what I really need is to find the benefits that started after a certain date. So:

public function index(Company $company)
{
    $employees = $company
                ->hasManyThrough('App\Employees', 'App\Departments');

    foreach ($employees as $employee) 
    {

        $new_company_benefits = $employee->benefits->where('starts_on', '>=', '2019/01/01');

    }
}

Is there a way with Eloquent to do this that avoids having to do the whole foreach thing?

0 likes
5 replies
jlrdw's avatar

why would benefits have to be a great-grandchild, just make it a child of company.

nexxai's avatar

@JLRDW - Using his example, each employee's benefits date would be different, based on when they started with the company and/or when their probationary period concludes, for example.

staudenmeir's avatar
Level 24

Laravel has no native support for a direct relationship.

I've created a package for this case: https://github.com/staudenmeir/eloquent-has-many-deep

You can use it like this:

class Company extends Model
{
    use \Staudenmeir\EloquentHasManyDeep\HasRelationships;

    public function benefits()
    {
        return $this->hasManyDeep(Benefit::class, [Department::class, Employee::class]);
    }
}

$benefits = $company->benefits()->where('starts_on', '>=', '2019/01/01')->get();
1 like

Please or to participate in this conversation.