I am trying to show featured products like amazon i.e. two featured products at top, two in middle and two at bottom, with non-featured/normal products in between them(, just like amazon). I have a field featured in products table of which value is true or false if its featured or non-featured. Not able to find way to write a query for the same. Is it possible to do it using single query?
I also have to use pagination and sorting with the above.
if (request()->sortBy && request()->sortBy === 'featured') {
$usIt = $query;
$featuredProducts = $usIt->where('featured', 1)->inRandomOrder()->paginate(6);
$simpleProducts = $usIt->where('featured', 0)->paginate(6);
$count = count($featuredProducts) + count($simpleProducts);
if ($count === 12) {
$payload = $this->sortByFeatured($featuredProducts, $simpleProducts);
} else {
$payload = $query->paginate(12);//todo:fix this gives empty data
}
} else {
$payload = $query->paginate(12);
}
private function sortByFeatured($featuredProducts, $simpleProducts)
{
$data = [];
array_push($data,
$featuredProducts[0], $featuredProducts[1],
$simpleProducts[0], $simpleProducts[1], $simpleProducts[2],
$featuredProducts[2], $featuredProducts[3],
$simpleProducts[3], $simpleProducts[4], $simpleProducts[5],
$featuredProducts[4], $featuredProducts[5],
);
return $data;
}
What I am trying to do is to make two queries one with random featured products and another with normal paginated products and put featured products in top middle and bottom of paginated normal products. But I think I am not doing it the right way. Please guide/help.
I think you should have a seperate collection for featured products and in the blade you should have a different sections. I didn't understand your code entirely, so let me give a simplified solution so you can work on it.
$items = 12;
$products = Product::where('is_featured, 0)->paginate($items);
// I don't remember the key of items in the paginated collection.
// It's probably data, but you can find it, if it isn't.
$products->data = $product->data->chunk($items/2);
$featured = Product::where('is_featured, 1)->limit(6)->get()->chunk(2);
In blade
<div class="featured--top">
@foreach($featured[0] as $product)
...
@endforeach
</div>
<div class="main--top">
@foreach($products[0] as $product)
...
@endforeach
</div>
<div class="featured--center">
@foreach($featured[1] as $product)
...
@endforeach
</div>
... and other parts.