使用嵌套的foreach在laravel中显示帖子和评论

时间:2018-01-17 07:57:50

标签: laravel foreach nested

如何使用嵌套的foreach在laravel中显示帖子和评论?

这是我的路线:

Route::get('/showpost', function () {
    $showpost = Posts::all();
    $comment = Comment::all();
    return view('showpost', compact('showpost', 'comment'));
});

这是我的观点:

            <h1>Posts :</h1>
            @foreach($showpost as $showpost)

                <h1>{{ $showpost->Title }}</h1>
                <h5>{{ $showpost->Content }}</h5>

                {{ Form::open(array('url'=>'showpost','method'=>'post')) }}

                   <h5>{{ Form::label('Comment : ') }} {{ Form::text('Comment') }}</h5>
                    {{ Form::hidden('invisible', $showpost->ID) }}
                    {{ Form::submit('Send Comment') }}

                {{ Form::close() }}

                <hr style='margin-top: 10%'>

            @endforeach

            <hr>
            <h1>Comments :</h1>
            @foreach($comment as $comment)
            {{ $comment->Comment }} -> {{ $comment->PostID }} <br>
            @endforeach

帖子显示在这里,其下面的文本框也显示,我们可以添加评论 我想对每个帖子下的帖子发表评论

现在我不能使用嵌套的foreach !!!

1 个答案:

答案 0 :(得分:1)

你应该使用雄辩的relationship()。在您的帖子const -

model

然后在你的public function comments() { return $this->hasMany('App\Comment'); } -

controller

$showposts = Posts::with('comments')->get(); return view('showpost')->with('showposts', $showposts); -

view

这样您就可以 <h1>Posts :</h1> @foreach($showposts as $showpost) <h1>{{ $showpost->Title }}</h1> <h5>{{ $showpost->Content }}</h5> {{ Form::open(array('url'=>'showpost','method'=>'post')) }} <h5>{{ Form::label('Comment : ') }} {{ Form::text('Comment') }}</h5> {{ Form::hidden('invisible', $showpost->ID) }} {{ Form::submit('Send Comment') }} {{ Form::close() }} <hr style='margin-top: 10%'> <hr> <h1>Comments :</h1> @foreach($showpost->comments as $comment) {{ $comment->Comment }} -> {{ $comment->PostID }} <br> @endforeach @endforeach comments相关联。