Search code examples
laraveleloquenteloquent-relationship

How to get all (parent) data and load their children data (eager load) but with condition on parent column?


let say I want to get all users and their posts only if user.status is true.

How to achieve this using eager loading (i.e with)

data I wanted to get:

{
"users": [
    {
        "id": 1,
        "status": false
    },
    {
        "id": 2,
        "status": false
    },
    {
        "id": 3,
        "status": true,
        "posts": [
            {
                "id": 1,
                "comment": "abc"
            },
            {
                "id": 2,
                "comment": "abc"
            },
            {
                "id": 3,
                "comment": "abc"
            }
        ]
    }
]

}


Solution

  • You can easily achieve this by loading all users, then filtering the ones you want to load, and finally eager load their relationship.

    $users = User::all();
    $users->filter->status->load('posts');