Laravel's Illuminate paginator can't find query string

1.8k views Asked by At

I'm working on a old PHP project, that is running in legacy SQL query, which is good but I like to use query builders like Laravel Illuminate SQL package!

So i have added all required package dependencies to run Illuminate SQL, and this query builder seems to work fine with pagination!

$users = Capsule::table('users')->paginate(1)->toArray();

But, the paginator seems not to be able to listen the query string! For example, by running the above code it would give some properties like, next_page , previous_page etc...

enter image description here

And when I try to pass the query string in the URL it can't fetch the data from query string(From the GET request)!

Visiting this page http://app.app/?page=2 would give the same result set.

How i should configure the Illuminate sql package so it can also listen to the query strings?

EDIT

Also, i've tried to use the illuminate/http package, but the $request->all() method always returns an empty array! Here is the code:

<?php
  require_once './vendor/autoload.php';
  use \Illuminate\Http\Request;

  $req = new Request();

  echo '<pre>';
  print_r($req->all());
  echo '</pre>';

It returns empty input data array, enter image description here

What i am missing to use the http package, any idea would be helpful.

3

There are 3 answers

7
Jonas Staudenmeir On BEST ANSWER

You have to set a page resolver:

\Illuminate\Pagination\Paginator::currentPageResolver(function ($pageName = 'page') {
    return (int) ($_GET[$pageName] ?? 1);
});

Laravel uses this resolver.

5
nice_dev On
  • You need to fetch the query string in the controller to pass the get parameter to paginate.

  • You can use the Illuminate\Http\Request class to receive and use the HTTP payload.

Your controller file:

<?php

use Illuminate\Http\Request;
class YourControllerClassName{
    public function someFunction(Request $request){
         echo "<pre>";
         print_r($request->all());
         print_r($request->input('page'));
         $users = Capsule::table('users')->paginate($request->input('page'))->toArray();
    }
}
0
Marcin Nabiałek On

You need to notice, that paginator won't use other parameters for query string - it just uses page parameter to get valid results page. But for example if you use:

http://app.app/?page=2&price=2

it won't take from database results with price = 2 - it's your job to do this.

However the 2nd thing are urls generated by paginator.

If you do it like this:

$users = Capsule::table('users')->paginate(1);

You can also use in next line

$users->appends(request()->except('page'));

This will add all other parameters from query string (except page) to urls, so first_page_url will then contain all other parameters from request.

You can also wrap it using fluent syntax like this:

$users = Capsule::table('users')->paginate(1)->appends(request()->except('page'));