Comments Table
+----+---------+------+------+--------+-----------+
| id | post_id | name | text | status | timestamp |
+----+---------+------+------+--------+-----------+
| 1 | 52 | user | test | 1 | timestamp |
+----+---------+------+------+--------+-----------+
Posts
+----+--------+------------------+-----------+
| id | title | description | timestamp |
+----+--------+------------------+-----------+
| 52 | mypost | post description | timestamp |
+----+--------+------------------+-----------+
Commnet.php [laravel Model]
public function post()
{
return $this->belongsTo('App\Post');
}
Post.php [laravel Model]
public function comments()
{
return $this->hasMany('App\Comment');
}
I want to List all Comments with Post title.
How can I collect Post title included in comments collection?
I do not want to use DB::table(); I want it to be collected through comment Model. like this $comments = Comment::all()->post->title;
My Answer:
belongsTo('App\Post', 'post_id', 'id');_}_ __Controller.php_ $comments = Comment::with('post')->get(); return view('comments.index', compact('comments')); __Blade View_@foreach($comments as $comment)
{{ $comment->post->title }}
{{ $comment->text }}
@endforeach
Rate this post
4 of 5 based on 3587 votesComments