【发布时间】:2018-01-14 06:38:36
【问题描述】:
我正在使用 laravel 集合 random 在单个帖子刀片中获取其他一些帖子,但问题是当我没有超过 6 个帖子时,我会收到错误
You requested 6 items, but there are only 1 items in the collection.
所以现在我需要做一个 if 语句来说明从 0 到 6 的随机帖子,这意味着例如如果我只有一个帖子并且我正在查看该帖子,那么忽略获取其他帖子(因为有没有其他帖子!),如果我总共有 2 个帖子,则只获得其他帖子,依此类推......直到随机顺序最多 6 个帖子。
这是我的功能:
public function show($slug) {
$post = Post::where('slug', $slug)->firstOrFail();
$postfeatures = Post::all()->random(6);
$subcategories = Subcategory::with('posts')->get();
$categories = Category::all();
$advertises = Advertise::inRandomOrder()->where('status', '1')->first();
return view ('frontend.single', compact('post', 'categories', 'subcategories', 'postfeatures', 'advertises'));
}
这是我的看法:
<ul class="gallery">
@foreach($postfeatures as $postss)
<li><a data-toggle="tooltip" data-placement="top" title="{{ $postss->title }}" href="{{ route('frontshow', $postss->slug ) }}"><img src="{{ url('images/') }}/{{ $postss->image }}" class="img-responsive" alt="{{ $postss->title }}"></a></li>
@endforeach
</ul>
谢谢。
【问题讨论】: