'Laravel get user data with profile
I have user and profile models with followers/following. What I want is to get the User data with the Profile data merged when calling Profile::followers. Now I only retrieve the profile data.
So I added the user() to Profile.php so I can call Profile::followers->user()... but no result. Can someone explain how to merge the User with Profile when calling the following()
function?
User.php model
public function following()
{
return $this->belongsToMany(Profile::class);
}
public function profile()
{
return $this->hasOne(Profile::class);
}
Profile.php model
public function followers()
{
return $this->belongsToMany(User::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
Solution 1:[1]
I don't know if I came late but the correct way to get a user profile would be
$profile = Auth::user()->profile;
I don't know if this would help, using Auth::user()
you get to fetch the current user and since you have a relationship with the profile you can call the profile()
public function without the braces.
I hope this helps anyone.
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 | Bobby |