2017-08-07 93 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

感謝男人現在的作品。 –