PHP Laravel alternate push based on condition

Viewed 64

I have fields in the table most_viewed and top_rated

    $most_viewed_posts = Blog::where('most_viewed', 1)->orderBy('created_at', 'desc')->get();
    $top_rated_posts = Blog::where('top_rated', 1)->orderBy('created_at', 'desc')->get();
    $featured_collection = collect();
    foreach ($most_viewed_posts as $most_viewed_post)
        $featured_collection->push($most_viewed_post);
    foreach ($top_rated_posts as $top_rated_post)
        $featured_collection->push($top_rated_post);
    $featured_posts = $featured_collection->sortBy('id', SORT_NUMERIC)->reverse()->chunk(2);

What i'm trying to accomplish here is im chunking the results into 2. Because Im displaying it like on the picture below. It's a carousel. The first result in a chunk should be most_viewed and the second is top_rated.

enter image description here

Now the issue is sometimes, most_viewed post is in Top Rated column. Is it possible that the items in the chunk is always most_view and top_rated?

1 Answers

Why do you accomplish it in so complicated way? Why not simply:

$most_viewed_post = Blog::where('most_viewed', 1)->orderBy('created_at', 'desc')->first();
$top_rated_post = Blog::where('top_rated', 1)->orderBy('created_at', 'desc')->first();
$featured_posts = collect([$most_viewed_post, $top_rated_post]);

Upd.

To get a collection of pairs Most Viewed + Top Rated you can use zip() method (https://laravel.com/docs/8.x/collections#method-zip):

$most_viewed_posts = Blog::where('most_viewed', 1)->orderBy('created_at', 'desc')->get();
$top_rated_posts = Blog::where('top_rated', 1)->orderBy('created_at', 'desc')->get();

$featured_collection = $most_viewed_posts->zip($top_rated_posts);

//later you can iterate them this way:
foreach($featured_collection as [$most_viewed, $top_rated]) {
    //...output
}
Related