Support the ongoing development of Laravel.io →
Eloquent
Last updated 3 months 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

Sign in to participate in this thread!

LaraJobs

Your banner here too?

Moderators

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

Your logo here?

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

© 2022 Laravel.io - All rights reserved.