Eltyer
Eltyer

Reputation: 697

Formatting Laravel JSON Object with relations

My goal is to output JSON for an API like this:

[
    {
        "id": 3,
        "name": "QUbkaUJhNm",
        "email": "[email protected]",
        "created_at": null,
        "updated_at": null,
        "profile": {
            "a": "value",
            "b": "value",
            "c": "value"
        }
    },
    {
        "id": 5,
        "name": "lYXmtkKuX9",
        "email": "[email protected]",
        "created_at": null,
        "updated_at": null,
        "profile": {
            "a": "value",
            "b": "value",
            "c": "value"
        }
    }
]

I have two models.

The User Model:

public function profile() 
{
     return $this->hasOne(Profile::class);
}

The Profile Model:

public function user() 
{
     return $this->belongsTo(User::class);
}

What should the code for my APIcontroller be?

$users = User::all();

...

Thank you!

Upvotes: 3

Views: 34

Answers (1)

Jose Rojas
Jose Rojas

Reputation: 3520

You can use Eager Loading like this:

return User::with('profile')->get();

if you want the result paginate

return User::with('profile')->paginate();

Upvotes: 2

Related Questions