spacedog4's avatar

Filter a model and stay with the pagination

I have a list, let call it Tasks, I can get all the tasks and paginate

Tasks::paginate(10);

But I also have a filter so I can do something like this

Tasks::where('name', 'LIKE', '%'.request('filter').'%')->paginate(10);

But if I'm in second page, and filter starting from the second page, it will filter and try to return the tasks from the second page, being that after the filter it has only one page

What can I do? I cant remove the page query if filter exists cause my filter can return more than 10 items

0 likes
1 reply
jlrdw's avatar

You append your filter to the query string.

In controller:

$pagelinks = array('psch' => $dogsearch, 'aval' => $aval);
// or whatever your data is

In the view:

echo '<td>' . $dogs->appends($pagelinks)->links() . '</td>';

Convert to blade, example is not blade.

Taylor has example of appending query string in the docs.

Appending To Pagination Links

You may append to the query string of pagination links using the appends method. For example, to append sort=votes to each pagination link, you should make the following call to appends:

{{ $users->appends(['sort' => 'votes'])->links() }}

Also if not using query string, you have to pass this stuff as parameters. You need to study the docs if that is the case and learn how to do this stuff.

https://laravel.com/docs/5.7/routing#route-parameters

It's all there in the docs.

Passing a basic parameter

View (convert to blade):

<?php $myvar = 'whatever'; ?>  // whereever the variable comes from, it's your app
 <a href="<?php echo DIR . 'mytest/' . $myvar; ?>">Click</a></td>

Route:

Route::get('mytest/{myvar}', 'DogController@myTest');

Cotroller:

    public function myTest($param = null)
    {
        echo $param;
    }

It's just that easy.

There have been many lengthy discussions on parameters and routing here on the forum FYI.

Also one of the answers had this: https://github.com/spatie/laravel-paginateroute

Please or to participate in this conversation.