【问题标题】:Have a way to just show the last item from my db, in a view with @foreach?有办法在@foreach 的视图中显示我的数据库中的最后一项吗?
【发布时间】:2019-10-13 07:57:47
【问题描述】:

有办法使用@foreach 将我的数据库中添加的最后一项显示到我的家吗?

@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
                                    <div class="fs-rp-item">
                                        <div class="entry-image">
                                            <!--<a href="#"><img src="/holy/images/blog/fs-thumb.jpg" alt="recent post"></a>-->
                                            <a href="#"><img src="/uploads/post/{{$post->id}}/image/{{$post->file_1}}" alt="recent post"></a>
                                        </div>
                                        <div class="entry-rp">
                                            <h4>
                                                <a href="#">{{$post->title}}</a>
                                            </h4>
                                            <p class="read-more">
                                                <a href="#">read the article</a>
                                            </p>
                                        </div>
                                    </div>
                                    @endforeach

【问题讨论】:

  • 你还没有做过吗?
  • 如果您只想显示最后一项,为什么要遍历循环?
  • 我考虑过使用 Laravel eloquent 模型来获取 DB 上的最后一条记录。它的工作原理类似于 Model ::all()->last() 。试试这个 Post::all()->last() 。你可以在这里查看更多选项stackoverflow.com/questions/16549455/…

标签: laravel


【解决方案1】:

我不太明白你的问题。对我来说,为了只显示最后一项而迭代循环是没有意义的。

无论如何,这是这样做的方法:

@foreach(App\Models\Post::orderBy('created_at','DESC')->get() as $post)
     @if($loop->last)
         // the end of the loop is reached at this point
     @endif
@endforeach

更好的方法是从控制器中的帖子中获取最新项目并将其传递给视图,并仅打印其数据:

use App\Models\Post; // at the top of your class

// your controller
public function index()
{
    $post = Post::latest()->first();
    return view('index', compact('post'));
}

然后在视图中您只需使用最新的帖子,例如:

<h4>
    <a href="#">{{$post->title}}</a>
</h4>

【讨论】:

    【解决方案2】:

    试试这个

    App\Models\Post::orderBy('created_at','DESC')->first()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多