I am working on a simple social network, i am working on the replies section now. I associated the post/status model with user as below, but when i tried to access in the vi
It seems like your are not attaching the replies to your $post
variable while passing it to your view.
We have to use with()
method to join these two tables.
Try, the following :
if(Auth::check()){
$posts = Post::notReply()
->where(function($query){
return $query->where('user_id', Auth::user()->id)
->orWhereIn('user_id', Auth::user()->friends()->lists('id'));
})
->with('replies')//Here we are joining the replies to the post
->orderBy('created_at', 'desc')
->get();
return view('timeline.index', compact('posts'));
}
Now, in your View you would need to use 2 foreach
loop like below:
@foreach($posts as $post)
{{--Your Code --}}
@foreach($post->replies as $reply)
{{--Your Code --}}
@endforeach
{{--Your Code --}}
@endforeach
Problem is with the postReply()
method. In old code you were overriding the $post
variable, due to which the reply was getting parent_id
as its own id
.
So, replace your old code with using $reply
variable.
old:
$post= Post::create([
'body' => $request->input("reply-{$statusId}"),
]);
$post->user()->associate(Auth::user());
$post->replies()->save($post);
new:
$reply = Post::create([
'body' => $request->input("reply-{$statusId}"),
]);
$post->user()->associate(Auth::user());
$post->replies()->save($reply);