1

How to use paginate with search result. I have this structure in my controller

public function searchFull(Request $request)
{
    if ($request->search) {
        $productsQty =  Product::with('images')
                        ->where('title', 'LIKE', "%$request->search%")
                        ->OrWhere('brand', 'LIKE', "%$request->search%")
                        ->OrWhere('slug', 'LIKE', "%$request->search%")->get()->count();

        $products  = Product::with('images')
                        ->where('title', 'LIKE', "%$request->search%")
                        ->OrWhere('brand', 'LIKE', "%$request->search%")
                        ->OrWhere('slug', 'LIKE', "%$request->search%")
                        ->paginate(3);
                        
        return view('product.search', compact('products', 'productsQty'));
    } else {
        return back();
    }
}

This is route file

Route::get('/search', [SearchController::class, 'searchFull'])->name('product.searchFull');

search works fine but when I trying use pagination it not working. it print paginate numbers but when click not working. when I check inspect url isn't correct

<a href="http://127.0.0.1:8000/search?page=2" class="relative inline-flex items-center px-4 py-2 -ml-px text-sm font-medium text-gray-700 bg-white border border-gray-300 leading-5 hover:text-gray-500 focus:z-10 focus:outline-none focus:ring ring-gray-300 focus:border-blue-300 active:bg-gray-100 active:text-gray-700 transition ease-in-out duration-150" aria-label="Go to page 2">
                                    2
                                </a>

url is "http://127.0.0.1:8000/search?page=2" insted of "http://127.0.0.1:8000/search?search=test&page=2"

How can I fix it

Tim Lewis
  • 27,813
  • 13
  • 73
  • 102
  • 1
    Does this answer your question? [How to automatically append query string to laravel pagination links?](https://stackoverflow.com/questions/24891276/how-to-automatically-append-query-string-to-laravel-pagination-links), specifically this answer: https://stackoverflow.com/a/63705458/3965631., or, in the documentation: https://laravel.com/docs/10.x/pagination#appending-query-string-values – Tim Lewis Jun 22 '23 at 16:03
  • The duplicate answers your question. You also don't need to fetch the product quantity separately, that is a waste of a query. The pagination already does this for you. `$products = Product::paginate(3); $productsQty = $products->total();` – andrewtweber Jun 25 '23 at 20:50
  • 1
    @andrewtweber Thanks for this correction it's so helpful for me – Irakli Qiria Jun 26 '23 at 15:24

0 Answers0