dionarap's avatar

Pagination on tag list

I'm having trouble paginating my tag page which lists all the products that are associated to a tag (many to many). The tag page is found on slug. I have the lists of products associated with the tag ordered on the the highest average rating from the reviews related to the products. Unfortunately i cannot seem to get the paginate working. What is the best way to do so?

Tables: products: id, name, price, approved tags: id, name, slug -products_tag: id, product_id, tag_id reviews: id, comment, rating, product_id

current code:

public function show($slug)
    {
        //
            $tag = Tag::with(['products' => function ($query) {
            return $query->where('approved', '=', 1)
                ->leftJoin('reviews', 'reviews.products_id', '=', 'reviews.id')
                ->select('products.*', DB::raw('AVG(rating) as ratings_average' ))
                ->groupBy('id')
                ->orderBy('ratings_average', 'DESC');}])->where('slug', $slug)->first();




        return view('tags.show')->withTag($tag);
    }
0 likes
1 reply
ftiersch's avatar
ftiersch
Best Answer
Level 28

I would split it up in two parts.

$tag = Tag::where('slug', $slug)->first();

$products = $tag->products()->where('approved', 1)
        ->leftJoin('reviews', 'reviews.products_id', '=', 'reviews.id')
                ->select('products.*', DB::raw('AVG(rating) as ratings_average' ))
                ->groupBy('id')
                ->orderBy('ratings_average', 'DESC')
        ->paginate(25);

That's still only 2 queries but you can use the paginate() method.

Please or to participate in this conversation.