'Laravel, get relationships of single record ($first on a with())
I want to add some related model data to my $user object. let me explain :
$user = User::find(1); // my user object
// I want to add my defined user profile from the user_profile relationship
$userdata = $user->with('user_profile')->first();
This doesn't work :( It returns the user profile of the first user in my db!
$user = User::find(1); // my user object
// I want to add my defined user profile from the user_profile relationship
$userdata = $user->with('user_profile')->get();
This isn't what I need either - user is always a single record in this scenario, not a collection.
So how do I get the related "with" data of $user, and store it in $userdata?
Thanks.
Solution 1:[1]
You are trying to get data of All users with associated user_profile with eager loading.
User::with('user_profile')->get();
if you want to get the data of single user you can try.
User::with('user_profile')->where('id',$user_id)->first();
using with('relations') will return all the users and associated data with them.
You can now access them from the object itself:
$user = User::with('user_profile')->where('id',$user_id)->first();
$userProfile = $user->user_profile;
if the $user is already fetched and you want to fetch the associated relationship.
Then you can
$user->load('user_profile');
Hope this helps
Solution 2:[2]
You can do it like this:
$user = User::with('user_profile')->where('id',$user_id)->first();
$user_profile_data = $user->user_profile;
Solution 3:[3]
Try below query
Here $user_id is id of the user whose data you want to fetch.
User::where('id', $user_id)->with('user_profile')->first()
Here you must define user_profile relation in user model
Solution 4:[4]
Try this to get related user_profile:
$userdata = $user->user_profile;
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Umair Tariq |
| Solution 3 | Nirali |
| Solution 4 | Sohel0415 |
