laravelpagination

How to Paginate a filtered Collection?


I have a function called priceFilter() that filters prodcuts based on the minimum and maximum price of a product.

This is the code:

public function pirceFilter(Request $request, Produit $produit)
{
    $produit = Produit::query();
    $min = $request->min;
    $max = $request->max;
    $product = DB::table('produits')
        ->select('*')
        ->whereBetween('prix_vent', [$min, $max])
        ->paginate(2)
        ->withQueryString();

    return view('filter-products', compact('product', 'min', 'max'));
}

And this is my view code:

<div class="mt-10 hidden sm:flex sm:flex-1 sm:items-center justify-center">
    <div>
        <nav class="isolate inline-flex -space-x-px rounded-md shadow-sm" aria- label="Pagination">
            {{ $product->links('pagination::tailwind') }}
        </nav>
    </div>
</div>

The links() function works fine and I get the pages like this below:
enter image description here

The issue is that when ever I want to show the second page I lose the filter and it shows me an empty page.

Unfortunately I am a bit new to laravel so I haven't tried anything, I am kinda lost here.


Solution

  • Instead of using the DB::table method, utilize Laravel's Eloquent to retrieve the filtered products. This ensures the filter parameters are automatically included in the pagination links.

    I don't know why you are injecting the Produit, anyhow I have changed $product to $products.

    public function priceFilter(Request $request, Produit $produit)
    {
        $min = $request->min;
        $max = $request->max;
    
        $products = Produit::whereBetween('prix_vent', [$min, $max])
            ->paginate(2)
            ->withQueryString();
    
        return view('filter-products', compact('products', 'min', 'max'));
    }
    

    And if you don't want to use Eloquent you can easily append the filter parameters to the pagination links.

    $product->appends(['min' => $min, 'max' => $max]);