Vinod VT
Vinod VT

Reputation: 7149

Laravel pagination is not working in search page

I am using laravel 5.1. This is my code,

routes.php

Route::any('users/search', array('as' => 'adminuserssearch', 'uses' => 'UsersController@adminSearch'));

UsersController.php

public function adminSearch(){
    $input = Input::all();
    if(!empty($input)){
        $key = Input::get('key');
        $users =  User::where('users.name', 'like', '%'.$key.'%')
         ->orWhere('users.email', 'like', '%'.$key.'%')
         ->paginate(10);

        return view('admin.users.search', ['users' => $users,'tag' =>$key]);
    }
}

search.blade.php

{!! $users->render() !!} //Use this code for display pagination.

When I search for a user, the url is like,

http://myproject/admin/users/search?key=user

But when I click pagination link the url will be like,

http://myproject/admin/users/search/?page=2

the ?key=user section will be lost from the url. How can I fix this problem ?

Upvotes: 1

Views: 4107

Answers (5)

Tarikul Parvez
Tarikul Parvez

Reputation: 1

use withQueryString() after paginate as like ->paginate(10)->withQueryString()

Upvotes: 0

Arnoldkk
Arnoldkk

Reputation: 587

In Laravel 8 change your UsersController.php by adding ->withQueryString() to ->paginate(10) e.g

public function adminSearch(){
$input = Input::all();
if(!empty($input)){
    $key = Input::get('key');
    $users =  User::where('users.name', 'like', '%'.$key.'%')
     ->orWhere('users.email', 'like', '%'.$key.'%')
     ->paginate(10)->withQueryString(); //add withQueryString()

    return view('admin.users.search', ['users' => $users]);
         }
   }

Yourwelcome: Source

Upvotes: 2

Luke Benson
Luke Benson

Reputation: 63

A solution that worked for me:

https://laravel.io/forum/11-15-2016-ho-to-paginate-search-results

The accepted solution says:

in your view where you display pagination...

{{ $results->appends(Request::except('page'))->links() }}

Upvotes: -2

SuperDicq
SuperDicq

Reputation: 46

You can costumize the paginator URL using the setPath() method.

You can add it to your controller like this $users->setPath('custom/url');

Upvotes: 0

Abdou Tahiri
Abdou Tahiri

Reputation: 4408

You should append this param to your pagination links .

{!! $users->appends(['key' => $tag])->render() !!}

Upvotes: 2

Related Questions