0

i followed the convention to avail the required data with compact method to view Schema User Table

id,name,email,password

Schema post Table

id,user_id,title,body,photo

Schema comment Table

id,post_id,user_id,comments,photo

in user model

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

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

in post model

Public function User()
{
  return $this->belongsTo('App\User');
}

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

}

in comment model

public function posts()
{
 return $this->belongsTo('App\post');
}

in controller

$list = User::with('post','comments')->paginate(1);

  return view('dynamic',compact('list'));

in view

@foreach($lists->comments as $comments)
{{$comments->name}}
@endforeach

post showing successfully according to users

and comments showing successfully according to posts

but commented name not showing up // please help

how to make relationship for fetch comments with commented user name

please help thanks in advance

3
  • please help i am trying to 2 days
    – shiv
    Commented Jul 16, 2018 at 9:22
  • 1
    try this $list = User::with('post.comments')->paginate(1);
    – rkj
    Commented Jul 16, 2018 at 9:22
  • 1
    always use singular function name for belongsTo relation and plural function name for hasMany
    – rkj
    Commented Jul 16, 2018 at 9:30

2 Answers 2

0

you have to change your code as below

@foreach($lists->comments as $comments)
    {{$comments->posts->user->name}}
@endforeach

or

you need to add relationship to your comment model as below

  Public function User()
{
  return $this->belongsTo('App\User');
}

after that you need to change your code as below

@foreach($lists->comments as $comments)
    {{$comments->user->name}}
@endforeach
0

change code as below in your view:

@foreach($lists->comments as $comments)
    {{$comments->User->name}}
@endforeach

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.