Support the ongoing development of Laravel.io →
Eloquent
Last updated 2 years ago.
0

Hey,

to get the values of a relationship (so the related models) you use the relationship-method as an attribute like this:

$jsonResponse['addresses'] = $user->addresses;

If you use it as a function call you get the querybuilder object so you could use it further like this:

$jsonResponse['addresses'] = $user->addresses()->wherePostcode('12345')->get();

But you can also shorten your code and use eager loading and the json response like that:

$user = User::with('addresses')->find($userId);

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

Perfect, thank you

0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.