Robert Nicjoo
Robert Nicjoo

Reputation: 365

Laravel collection with if condition

I'm using laravel collection random to get some of other posts in single post blade but the problem is when i don't have more that 6 posts i'll get error of You requested 6 items, but there are only 1 items in the collection.

So now I need to make an if statement to say get random posts from 0 to 6 which means if for example i have only one post and i'm in view of that post so ignore of getting other posts (cause there is no other post!) and if i have 2 posts in total get only other one and so on... till maximum 6 posts in random order.

here is my function:

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'));
    }

Here is my view:

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

Thanks.

Upvotes: 2

Views: 1949

Answers (2)

Jorge Y. C. Rodriguez
Jorge Y. C. Rodriguez

Reputation: 3449

For anyone coming to this question, the accepted answer is really heaver recourse and it will not work in a real life project with a lot data.

Instead you can do something like this:

$builder = Post::query();
$postFeatures = $builder
                 ->inRandomOrder()
                 ->when($builder->count() > 6, function ($query) {
                       return $query->limit(6)
                 })->get();

This will make sure sql only return what we actually need instead all the possible posts in record.

Upvotes: 2

Vu Hoang Duc
Vu Hoang Duc

Reputation: 312

You can count your collection

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

Hope it help!

Upvotes: 1

Related Questions