Issue
I am trying to display the post title that user comment belongs to on his profile page.
This is what I'm doing on the user's profile
public function show($user, Post $post)
{
$user = User::whereName($user)->with('posts.votes')->with('comments')->firstOrFail();
$comments = $user->comments;
$linkKarma = User::find($user->id)->votes()->sum('value');
$commentKarma = User::find($user->id)->commentvotes()->sum('value');
$total_comments = $user->comments->count();
$isModerator = false;
return view('user/profile')->with('user', $user)
->with('linkKarma', $linkKarma)
->with('commentKarma', $commentKarma)
->with('comments', $comments)
->with('total_comments', $total_comments)
->with('isModerator', $isModerator);
}
I am basically getting everything he has, from posts
, votes
and comments
- However, I am not able to show the post that these comments belong to on the user profile page.
I can use $comment->post_id
within a foreach()
but that will only get me the post ID but I can't use $comment->post->title
it will error Trying to get a property of a none object
How can I do that?
My Database
posts: id, title, user_id, subreddit_id...
comments: id, comment, user_id, post_id...
user: id, name, email...
Post
Model
public function user() {
return $this->belongsTo('App\User');
}
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
public function votes() {
return $this->hasMany('App\Vote');
}
public function moderators() {
return $this->hasMany('App\Moderator');
}
public function comments() {
return $this->hasMany('App\Comment');
}
Comment
Model
public function posts() {
return $this->belongsTo('App\Post');
}
public function user() {
return $this->belongsTo('App\User');
}
public function commentvotes() {
return $this->hasMany('App\CommentVote');
}
public function subreddit() {
return $this->belongsTo('App\Subreddit');
}
User
Model
public function subreddit() {
return $this->hasMany('App\Subreddit');
}
public function posts() {
return $this->hasMany('App\Post');
}
public function votes() {
return $this->hasManyThrough('App\Vote','App\Post');
}
public function commentvotes() {
return $this->hasManyThrough('App\CommentVote','App\Comment');
}
public function moderators() {
return $this->hasMany('App\Moderator');
}
public function comments() {
return $this->hasMany('App\Comment');
}
Solution
Try this:
$comment->posts->title
(notice it is "posts" not "post")
Your Comment model has the function posts
so when you access it from the comment, you access it with that function name, as shown above.
I would rename posts to post, as a comment belongs to ONE post, not multiple posts.
Also change
$user = User::whereName($user)->with('posts.votes')->with('comments')->firstOrFail();
to be
$user = User::whereName($user)->with('posts.votes', 'comments.posts')->firstOrFail();
Answered By - Daniel Twigg
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.