Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use laravel with() method in another to get value

I am currently fetching and display some data from my API with the below code:

My code

public function getTheUser()
{
return User::where('user_id', '10')
        ->with('position')
        ->get();
}

API display result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
    {
        id: 10,
        name: Mary,
        gender: Female,
        position: [
            id: 1,
            position: Executive,
        ]
    }
]

I want to add ->with(role) inside position to get the below desired results

Desired result

[
    {
        id: 10,
        name: Mary,
        gender: Female,
        position: [
            id: 1,
            position: Executive,
            role: [
                id: 1,
                role: Manager,
            ]
        ]
    }
]

I will need your help Thanks in advance.

>Solution :

You should try using nested eager loading

public function getTheUser()
{
return User::where('user_id', '10')
        ->with('position.role')
        ->get();
}

It is described in more detailed way here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading