0

I was reading the Laravel documentation and unfortunately it didn't tell me how to make composite JSON objects.

http://laravel.com/docs/master/eloquent-serialization

So right now I have two entities: User and Post and I want to return a JSON object containing the User as the parent (JSON) and Posts as the children of User (JSON) in the JSON object. There is a one-to-many relationship between User and Post.

Here is the controller method I want to change:

public function show($user)
{
    return $user;
}

2 Answers 2

1

You just need to fetch the the relationship when querying a user:

$user = User::find(123)->with('posts')->get();

Then return a JSON response.

return response()->json($user);

Happy coding!

Sign up to request clarification or add additional context in comments.

Comments

0

In addition to Rubens Mariuzzo answer, if you haven't done this, you first need to declare relationship in your model

# User Model
public function posts()
{
    return $this->hasMany('\App\Post');
}

Then you will be able to do as Rubens Mariuzzo stated

$user = User::find(123)->with('posts')->get();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.