samedi 24 octobre 2015

Laravel 5: show me the post title that this comment belongs to on user profile

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');
}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1Mijhre
via IFTTT

Aucun commentaire:

Enregistrer un commentaire