I\'m having some trouble with my pagination. I\'m having two tables with data from a database and I paginated it with laravel Paginator.
Now my problem is when you g
Laravel 5.7
Model->paginate(10, ['*'], 'paramName');
10 = Max items per page
['*'] = colums
paramName = pagination param name
Illuminate\Database\Eloquent\Builder
Unfortunately I can't test this code right now, but browsing at the docs and the code (in Illuminate/Pagination/Environment
) I guess you could something like this:
# use default 'page' for this
$collection1 = Model::paginate(20);
# use custom 'other_page' for this
$collection2 = Model2::paginate(20);
$collection2->setPageName('other_page');
The setPageName()
method isn't documented in the docs, but it's a public method alongside those indicated in the documentation, so it should be working fine. FOr reference, this is the declaration (l. 171-180 in vendor/laravel/framework/src/Illuminate/Pagination/Environment.php
):
/**
* Set the input page parameter name used by the paginator.
*
* @param string $pageName
* @return void
*/
public function setPageName($pageName)
{
$this->pageName = $pageName;
}
Now take into consideration that you will have another query string appended to the url, so you need to tell the pagination to consider it. Use the appends() method:
$collection1->appends(array_except(Request::query(), 'page'))->links();
$collection2->appends(array_except(Request::query(), 'other_page'))->links();
That is, tell each Presenter to build up the url with all the query strings (the array resulting from Request::query()
without the current index used by the paginator, or you'll end up with a double value). array_except()
is a Laravel built in array helper that returns the given array (1st parameter) purged of the passed index (2nd parameter).
I'll try to test this code as soon as I can, but it should work. Let me know in any case!
Use:
$var1 = DB1::orderBy('...')->paginate(5, ['*'], '1pagination');
$var2 = DB2::orderBy('...')->paginate(5, ['*'], '2pagination');
For Laravel 5.2
In Laravel 5.2, declare the page name when using paginate()
.
Here is an example that works with multiple paginators on a page.
$pageName
for other models.See the method \Illuminate\Database\Eloquent\Builder::paginate()
/**
* Get things by ownerId
*
* @param integer $ownerId The owner ID.
*
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator Returns a pagination instance.
*/
public function getThings($ownerId)
{
$builder = \App\Models\Things::where('ownerId', '=', (integer) abs($ownerId));
// dd([
// '__METHOD__' => __METHOD__,
// '__FILE__' => __FILE__,
// '__LINE__' => __LINE__,
// '$ownerId' => $ownerId,
// 'sql' => $builder->toSql(),
// '$builder' => $builder,
// 'paginate' => $builder->paginate($perPage = null, $columns = ['*'], $pageName = 'p', $page = null),
// ]);
return $builder->paginate($perPage = null, $columns = ['*'], $pageName = 'p', $page = null);
}
Note: $pageName = 'p'