How to join the query string in Laravel 4 pagination?

Asked

Viewed 250 times

4

How do I join query string in the 4-way pagination?

For example: I have a data listing and on this screen I have a search filter. When I send a get to request the filter in the list by the url http://localhost/lista-de-produtos?marca=1, the data is listed as requested, but when I go to page 2 the paginate removes the parameter mark=1 from the url and adds pag=2, then the filter does not work.

Follow the code of the consultation:

$registros = Produtos::where(function ($query) {
    if (Input::has('nome')) {

        $nome = Input::get('nome');

        $query->where('nome', 'LIKE', "%{$nome}%");

    } 

    if (Input::has('marca')){
        $marcaId = Input::get('marca');

        $query->where('marca_id', '=', $marcaId);
    }

})->paginate(20);
  • There have been people who have used http_build_query to do this. But in Laravel you don’t have to. It’s all beautiful. See the answer ;)

2 answers

4


In the Laravel there is a method called appends, where you pass an array, which will represent the data that will go along with the attribute page at the url.

Example:

User::where('admin', '=', 0)->paginate()->appends(Input::except('page'));

In that case, the Input::except will be in charge of adding all of the current query string to your paging.

This is very useful in case of searches with paging, as in Google.

Instead of excepts, you can also use Input::all().

Updating

In more recent versions on Laravel 5, it was not necessary to do this. But if you need it, the logic is the same:

User::where('admin', '=', 0)->paginate()->appends($request->all());

2

The model Products does not know the parameters passed in the filter. In order to identify them, it is necessary to instruct you to pass the parameters in the construction of pagination links.

This is done using the method appends (See the documentation of the Laravel). For example, in Blade, if you are using like this:

{{ $registros->links() }}

Then implement so:

{{ $registros->appends([
  'nome'  => Request::input('nome'),
  'marca'  => Request::input('marca'),
])->links() }}

or so if Laravel 5.6+:

{{ $registros->appends(request()->all())->links() }}

or directly on the model:

Produtos::when(...)->appends(request()->all())->paginate(20);

This way, paging will include array keys as parameters in the links querystring.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.