如何在注释中显示用户


How to display the user in comment

我的应用程序中有一个评论框,它运行良好。但我想显示在我的帖子中发表评论的用户,我该如何做到这一点?到目前为止,我有这个代码。

这是我的观点

<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();