[SOLVED] Laravel, get relationships of single record ($first on a with())

Issue

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

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

Answered By – PHP Dev

Answer Checked By – Marilyn (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *