Yorkata's avatar

Pagination + Search problem

My pagination is not working when I try to search for something.

When I try to search test the URL is like that: /search?query=test

When I change the page with pagination link the URL is like that: /search?page=2 and the table with results is empty

Route:

Route::get("/search", [CompetitionController::class, 'index'])->name('search_bar_route');

Function in Controller

  public function index()
    {   
        $competitions = Competition::orderby('id','DESC')->paginate(40);
        if(isset($_GET['query'])){
            $search_bar_input = $_GET['query'];
            $competitions = Competition::orderby('id','DESC')->where('name', 'LIKE', '%'.$search_bar_input.'%')->paginate(2);
            return view('competition.index', compact('competitions'));
        }else{
            return view('competition.index', compact('competitions')); 
        }
    }

In view:

 {{ $competitions->links() }}   

Any idea what I did wrong?

0 likes
3 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Make sure to preserve the query string

            $competitions = Competition::orderby('id','DESC')->where('name', 'LIKE', '%'.$search_bar_input.'%')->paginate(2)->withQueryString();
Sinnbeck's avatar

@Yorkata Happy to help. Mark a best answer to set the thread as solved, if it works now :)

2 likes

Please or to participate in this conversation.