Stack Overflow Asked by mrmar on December 28, 2020
I have three models and relationships. Post, UserProfile, User. I need to fetch name column value from users table but I need to go through posts and user profile to fetch it. Posts are connected to user profile and user profile is connected to users. I tried $post->userProfile()->user()->name but it won’t work. I get error
Call to undefined method Illuminate\Database\Eloquent\Relations\BelongsTo::user()
Here is my code. Any help is appreciated.
Post.php
posts table has user_profile_id column
public function userProfile()
{
return $this->belongsTo(UserProfile::class);
}
UserProfile.php
public function user()
{
return $this->belongsTo(User::class, 'id');
}
public function posts()
{
return $this->hasMany(Post::class);
}
User.php
public function profile()
{
return $this->hasOne(UserProfile::class, 'id');
}
You would want to use the dynamic properties to access the actual resolved relationship (Model or Collection) and not the relationship methods:
$post->userProfile->user->name
This would assume these relationships are setup correctly and exist in the database.
If you are using PHP8 you can use the existential operator to avoid the issue of a relationship returning null
and calling methods on that:
$post->userProfile?->user?->name
Correct answer by lagbox on December 28, 2020
Please try this.
// Lets get the post having id 1
$post = Post->find(1);
$post->userProfile->user->name;
When you are using parenthesis, you will get you the Eloquent relationship itself, not the results of that relationship.
$post->userProfile();
If you wanted to get user's profile information of that post by using parenthesis, then use this code.
$post->userProfile()->get(); //or
$post->userProfile()->first();
Answered by Ramesh KC on December 28, 2020
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP