首页 > 解决方案 > 有办法在@foreach 的视图中只显示我的数据库中的最后一项吗?

问题描述

有办法使用@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

解决方案


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

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

@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>

推荐阅读