Skip to content
Advertisement

Eloquent eager loading not working with nested fields

I’m trying to get User model with relations and nested fields. This first try is working fine:

$user = AppUser::where('id', auth()->user()->id)->with(['userdoc'])->get();

Its returning the entire userdoc object. But I want only two fields, so I’m trying:

$user = AppUser::where('id', auth()->user()->id)->with(['userdoc:id,number'])->get();

And this way it’s returning userdoc:null in toArray() JSON.

This seems to be ok according to with documentation at https://laravel.com/docs/5.5/eloquent-relationships#eager-loading

I’m on Laravel 5.6.

Adding some more information:

Without specific fields gets the entire object

$user = AppUser::where('id', auth()->user()->id)->with('userdoc')->get();
return response()->json($user->toArray(), 200);

[
    {
        "id": 11,
        "email": "xxxxx",
        "slug": "xxxxx",
        "created_at": "xxxxx",
        "updated_at": "xxxxx",
        "deleted_at": null,
        "first_name": "xxxxx",
        "last_name": "xxxxx",
        "is_verified": 0,
        "userdoc": {
            "id": 11,
            "created_at": "2018-08-20 13:20:29",
            "updated_at": "2018-08-20 13:20:29",
            "deleted_at": null,
            "user_id": 11,
            "type": "document",
            "number": "xxxxxxxxx"
        }
    }
]

Determining userdoc fields makes the object becomes as null

$user = AppUser::where('id', auth()->user()->id)->with('userdoc:id,number')->get();
return response()->json($user->toArray(), 200);

[
    {
        "id": 11,
        "email": "xxxxxxxxxxx",
        "slug": "xxxxxxxxxxx",
        "created_at": "xxxxxxxxxxx",
        "updated_at": "xxxxxxxxxxx",
        "deleted_at": null,
        "first_name": "xxxxxxxxxxx",
        "last_name": "xxxxxxxxxxx",
        "is_verified": 0,
        "userdoc": null
    }
]

Advertisement

Answer

You result is because you does not select related primary key user_id. Try this

$user = AppUser::where('id', auth()->user()->id)->with(['userdoc:id,user_id,number'])->get();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement