babu babu - 4 months ago 12
PHP Question

unable to fetch user data of comment in a post's view in laravel

I have three models and corresponding tables. User,Post,Comment.
Column of users table are id, name, email.
Column of posts table are id, title, body.
Column of comments table are id, user_id, post_id, comment.

User model has this function as below:

public function comments(){

return $this->hasMany('App\Comment');
}


Post model has this function as below:

public function comments(){

return $this->hasMany('App\Comment');
}


Comment model has these two functions as below:

public function user(){

$this->belongsTo('App\User');
}

public function post(){

$this->belongsTo('App\Post');
}


single post showing function in PostController is as below:

public function show($slug)
{
$post = Post::where('slug', $slug)->first();
return view('post.show')->withPost($post);
}


and in show.blade.php i'm trying to achieve this functionality:

@foreach($post->comments as $comment)
<p>
{{$comment->user->name}}
</p>
@endforeach


Why is it throwing error saying relationship method must return an object ?

Tom Tom
Answer

You need to return the relationship, so your code becomes:

public function user(){
    return $this->belongsTo('App\User');
}

public function post(){
    return $this->belongsTo('App\Post');
}
Comments