【问题标题】:use nested foreach for showing posts and comments in laravel使用嵌套的 foreach 在 laravel 中显示帖子和评论
【发布时间】:2018-06-26 00:59:58
【问题描述】:

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

这是我的路线:

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

这里显示帖子,下面也显示一个文本框,我们可以添加评论 我想向 cmets 展示每个帖子下的帖子

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

【问题讨论】:

  • 你的帖子和cmets之间的模型中添加了雄辩的关系吗?
  • 我建议您看看这个Laracast 系列,它将向您展示如何实现这样的关系。
  • 在阅读文档之前,您是否在数据库迁移中添加了外键?

标签: laravel foreach nested


【解决方案1】:

你应该使用雄辩的relationship()。在你的帖子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

这样您将获得与您的posts 关联的comments。

【讨论】:

  • 我在哪里写关系?
  • @Mohammad 正如我在回答中所说,在您的帖子模型中写下您的关系。我建议首先查看有关关系的 laravel 文档,然后再进一步。
猜你喜欢
  • 2021-05-14
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 1970-01-01
  • 1970-01-01
  • 2015-04-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多