如何在评论中显示用户

问题描述:

我在我的应用程序中有一个评论框,它的工作正常。但我想显示在我的文章中发表评论的用户,我该如何实现?到目前为止,我有这个代码。如何在评论中显示用户

这是我的看法

<div class="view-post"> 
     <div class="body"> 
      <h3>{{$posts->title}}</h3> 
      <h6>{{$posts->created_at->toFormattedDateString()}}</h6> 

      <p><img src="{{ asset('img/' . $posts->image) }}" class="img-rounded"/></p> 
      <p>{{$posts->content}}</p> 
     </div> 
     <hr> 
     <section> 
      <h5>LEAVE US A COMMENT</h5> 
      <form action="{{ URL::route('createComment', array('id' => $posts->id))}}" method="post"> 
       <div class="form-group"> 
        <input class="form-control" type="text" placeholder="Comment..." name="content">   
       </div> 
      <input type="submit" class="btn btn-default" /> 
      </form> 
     </section><br> 

     <section class="comments"> 
      @foreach($posts->comment as $comments) 
      <blockquote>{{$comments->content}}</blockquote> 
      @endforeach 
     </section> 

    </div> 

我的控制器

public function viewPost($id) 
    { 
     $post = Post::find($id); 
     $user = Auth::user(); 
     $this->layout->content = View::make('interface.viewPost')->with('posts', $post)->with('users',$user); 

    } 


public function createComment($id) 
    { 
     $post = Post::find($id); 


     $comment = new Comment(); 
     $comment->content = nl2br(Input::get('content')); 


     $post->comment()->save($comment); 

     return Redirect::route('viewPost', array('id' => $post->id)); 
    } 

在你的模型,你可以建立一个和另一个模型之间的关系。

就像那个..

用户模型

class User extends Model { 

    public function comments() 
    { 
     return $this->hasMany('App\Comment'); 
    } 
} 

评论模型

class Comment extends Model { 

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

所以,你可以得到

$comment = Comment::find(1); 
$user = $comment->user()->get(); 
012用户
+0

所以除了从用户到发布和发布评论关系,我必须这样做? – 2015-02-24 15:20:11

+0

我想是的。像这样尝试一次。 – Nick 2015-02-24 15:26:02