Home > Software design >  Use laravel with() method in another to get value
Use laravel with() method in another to get value

Time:07-19

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

[
    {
        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.

CodePudding user response:

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

CodePudding user response:

What I understand is you want to retrieve the position's child which can be done using

  return User::where('user_id', '10')
        ->with('position','position.role')
        ->get();

For more info: https://laravel.com/docs/8.x/eloquent-relationships#nested-eager-loading

  • Related