PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, July 8, 2022

[FIXED] how to fetch commented name on posts in laravel 5.4

 July 08, 2022     comments, eloquent, laravel, posts     No comments   

Issue

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


Solution

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


Answered By - Abhilash.k.p
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing