Search code examples
laravellaravel-5eloquenteager-loading

Get the user name and comment with article id in Laravel


I have 3 tables users, comments, and articles. I have a route like this:

Route::get('/article/{id}', 'ArticlesController@view');

What I want is when I accessing that route I will get User Name and their comment in this article id.

so here's my view function in ArticlesController:

public function view($id){
        $article = Article::with('comments')->find($id);
        return view('front.single',compact('article'));
}

and here's my single.blade.php code:

<div class="single-grid">
      @section('content')
         <h1>{{ $article->title }}</h1>
         <p>{{ $article->content }}</p>
      @show
</div>          

<div class="comment-list">
@foreach($article->comments as $comment)
    <ul class="comment-list">
    <div class="comment-grid">
        <img src="/images/avatar.png" alt=""/>
        <div class="comment-info">
            <h4>{{ $comment->user->name }}</h4>
            <p>{{ $comment->comment }}</p>
            <h5>{{ $comment->created_at->diffForHumans() }}</h5>
            <a href="#">Reply</a>
        </div>
        <div class="clearfix"></div>
    </div>
</ul>
@endforeach
</div>

I'm not sure what how to do it since it gives me error like this:

"Call to undefined relationship [comment] on model [App\User]."

I already define the relation in each model. here's my articles model:

public function comments(){
    return $this->hasMany(Comment::class);
}

public function user(){
    return $this->belongsTo(User::class);
}

My comment model:

 public function article(){
    $this->belongsTo(Article::class);
}
public function user(){
    $this->belongsTo(User::class);
}

and here's my User model:

public function articles(){
    return $this->hasMany(Article::class);
}
public function comments()
{
    return $this->hasMany(Comment::class);
}
public function publish(Article $article){
    $this->articles()->save($article);
}

here's my table structure: -users(id,name,email,password,remember_token,created_at,updated_at) -comments(id,user_id,article_id,comment,created_at,updated_at) -articles(id,user_id,title,content,created_at,updated_at)

so how can I can User Name just by using this route? thanks.


Solution

  • on Your Comment Model, You need to replace articles to article

    public function article(){
            $this->belongsTo(Article::class);
        }
    

    also, if you want to get user specific comments, than you need to change your controller action code from

    $article = Article::with('user.comment')->find($id) to
    $article = Article::with('user.comments')->find($id);