2017-08-07 95 views
0

我使用laravel收集random得到一些其他职位在单个刀片后,但问题是,当我没有更多的是6个帖子我会得到的 You requested 6 items, but there are only 1 items in the collection.Laravel收集与if条件

错误

所以现在我需要做一个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> 

感谢。

回答

1

你可以指望你的收藏

$count = count(Post::all()); 
if($count > 6){ 
$postfeatures = Post::all()->random(6); 
}else{ 
$postfeatures = Post::all()->random($count); 
} 

希望它能帮助!

+0

我知道,但它不是关于虚拟数据它是关于问题(错误),当我的应用程序生产不能在这个问题在线网站我不能添加虚拟数据! –

+0

sr我没有读过。请检查我更新的@RobertNicjoo –

+0

感谢男人现在的作品。 –