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

dchansen's avatar

Nested relationships and eager loading?

I don't know if this can be done with eloquent, or if I'm just not grasping how this works. I have an API where the platform, state, and loan_purpose are given, and I need to return a list of lenders associated with the platform, that supports the given loan_purpose and are licensed in the given state.

Here's what I've got thus far:

platforms
id,
name
loan_purposes
id,
name
states
id,
shortname,
longname
lenders
name,
enabled

I've created a model with a many to many relationships between platforms and lenders, but I don't know how to filter them based on whether or not they support the given loan_purpose in the given state.

SCENARIO: /api/?platform=2&loan_purpose=1&state=6

with this API request I need to return a list of lenders.

{
    {
        "id": 3,
        "name": "lender 3"
    }, {
        "id": 5,
        "name": "lender 5"
    }
}

UPDATE

I've tried adding a few pivot tables to help facilitate the relationships here, but I'm not sure if this is the most effective way to achieve this.

lender_platforms
id,
lender_id,
platform_Id,
enabled
lender_loan_purpose_states
id,
lender_id,
loan_purpose_id,
state_id

I first thought I would be able to do something like

<?php


App\Platform::with([
    'lenders'   => function($q) {
        $q->with([
            'loanPurposes' => function ($q) use ($loanPurpose) {
                $q->whereIn('loan_purpose_id`, [$loanPurpose, null]);
            },
            'states' => function($q) use ($state) {
                $q->whereIn('state_id', [$state, null]);

            }
        ]);
    }
])->find($platform_id);

However, it doesn't seem as though I'm fully grasping how eloquent builds relationships.

0 likes
2 replies

Please or to participate in this conversation.