Laravel将第一个Bootstrap横幅设置为Active


Laravel set first Bootstrap banner as Active

我目前正试图通过保存在数据库中的一堆横幅循环,我需要将第一个横幅设置为活动。我尝试过如果($banner->first) {{'active'}} endif,但这似乎不适合我,因为所有项目都被设置为活动。我想过将id设置为1,但如果有人删除了具有该id的图像,则会中断。这是我到目前为止的代码…

控制器:

public function index()
{
    //
    $banners = Banner::all();
    $pages = Page::all();
    return View::make('page')->with('banners', $banners, 'pages', $pages);
}

视图:

<div id="mainCarousel" class="carousel slide" data-ride="carousel">
    <div class="carousel-inner">
        @foreach($banners as $banner)
                <div class="item @if($banner->first()) {{ 'active' }} @endif">
                    <img style="width: 100%; height: 500px" src="{{ $banner->image }}" alt="{{ $banner->alt }}">
                </div>
        @endforeach
    </div>
    <a class="left carousel-control" href="#mainCarousel" data-slide="prev">
        <span class="glyphicon glyphicon-chevron-left"></span>
    </a>
    <a class="right carousel-control" href="#mainCarousel" data-slide="next">
        <span class="glyphicon glyphicon-chevron-right"></span>
    </a>
</div>

我也尝试了$banner->first()以及$banner->first(),并得到相同的结果。

m4tthumphrey在Laravel IRC聊天中给了我正确的答案。因此,如果有人遇到这个问题,我会在这里给你正确的答案。

我认为这是不言自明的,但Laravel基本上会找到你的数据库中第一个横幅的第一个ID,并匹配ID。

@if($banner->id === $banner->first()->id) {{ 'active' }} @endif

我刚刚发现这不是最好的解决方案,如果你在不同的页面有不同的横幅,如果是这种情况,那就试试。

@foreach($banners as $index => $banner) <div class="item @if($index == 0) {{ 'active' }} @endif"> <img style="width: 100%;" src="{{ $banner->image }}" alt="{{ $banner->alt }}"> </div> @endforeach