Okay,
So I can't figure this one out. Eloquent model is new to me.
I'm trying to fetch comments for specific posts.
This is my post model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function likes()
{
return $this->hasMany('App\Like');
}
public function comments()
{
return $this->hasMany('App\Comment');
}
}
Comment model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
public function user()
{
return $this->belongsTo('App\User');
}
public function post()
{
return $this->belongsTo('App\Post');
}
}
Routes:
public function getDashboard(){
$posts = Post::orderBy('created_at', 'desc')->get(); // MySQL ORDER BY
$comments = Comment::orderBy('created_at', 'desc')->get();
return view('dashboard', ['posts' => $posts], ['comments' => $comments]);
}
($comments might be unnecessary?)
View:
@foreach($posts as $post)
<article class="post" data-postid=" {{ $post->id }} ">
<p>{{ $post->body }}</p>
<div class="info">
Posted by {{$post->user->first_name}} on {{ $post->created_at }}
</div>
</article>
I tried to loop through the comments using:
@while($comments->post_id = $post->id)
<p>{{$comments->body}}</p>
@endwhile
I got an error message "Undefined property: Illuminate\Database\Eloquent\Collection::$body" even though the comments table have a column named "body".