1

I want to make a user wall where all of his post will be loaded with those who has given comment under it. So I have defined following relations in my User model.

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

My Post model:

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

My Comment model:

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

In my Controller:

public function wall($id)
{ 
  $all_post = Post::where('user_id',$id)->get();
  return view('client.wall',['all_post'=> $all_post]);
}

in my Blade file:

@foreach($all_post as $post)
Post Title: {{ $post->title }} //gets the title properly 
@foreach($post->post_comment as $comment) //this foreach loop throwing erros
Name: {{ $comment->user->name }}
Comment: {{ $comment->description }}
@endforeach
@endforeach

Probably my logic is wrong to load the comments from database. Because I am getting errors.

2
  • 2
    Can you add the errors you are getting to your question? Commented May 9, 2016 at 0:16
  • Ki build korteso tawsif bhai? XD Commented May 9, 2016 at 4:49

1 Answer 1

1

try this ad share if you still have an error

Controller

public function wall($id)
{ 
  $all_post = Post::where('user_id',$id)->with('post_comment')->get();
  return view('client.wall')->with('all_post',$all_post);
}

VIEW

@foreach($all_post as $post)
Post Title: {{ $post->title }} //gets the title properly 
  @foreach($post->post_comment as $comment) 
    Name: {{ $comment->user->name }}
    Comment: {{ $comment->description }}
  @endforeach
@endforeach
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.