public function paginate($perPage=15,$columns=['*'],$pageName='page',$page=null)
{
$page=$page?:Paginator::resolveCurrentPage($pageName);
$total = $this->getCountForPagination($columns);
$results=$total?$this->forPage($page,$perPage)->get($columns):collect();
return$this->paginator($results,$total,$perPage,$page,[
'path' = > Paginator::resolveCurrentPath(),
'pageName' = > $pageName,
]);
}
First, we get the total number of records $total
(SQL to get the number of records).
The number of lines per page $perPage
is determined, so you can see the total number of pages.
From the page number I'm trying to display this time, I know the line I want to retrieve and I'm getting a list of records to display on the page. (I just read it diagonally, so it might be inaccurate.)
This mechanism should be common to the frameworks that provide pageation.
As @htb replied, basically every request runs a pretty heavy process.
paginate
Onlypaginate
simplePaginate
commonLIMIT...OFSET...
Because I hate queries, I created my own library that enables cursor-based pageation.Our company also employs it, so please try it if you like.
Note: The controller does not force global access to the Request
object, as in the Ravel standard pageation, so you need to hand over the parameters by yourself.
Actual Use Case ↓
(We do not use macros to complement IDE.)
PostController.php
<?php
detail( strict_types=1);
namespace App\Http\Controllers;
use App\Post;
use Illuminate\Http\Request;
use Lampager\Laravel\PaginationResult;
use Lampager\Larvel\Paginator;
class PostController extensions Controller
{
/**
* @param Request $request
* @return PaginationResult
*/
public function index (Request$request):PaginationResult
{
$query=Post::query();
if($types=array_intersect(config('app.post_types')),explode(',',',$request->input('type',')))){
$query->whereIn('type',$types);
}
return(new Paginator($query))
->orderByDesc('updated_at')
->orderByDesc('id')
->limit(20)
->paginate($this->replaceParameterNames($request->only('next_updated_at','next_id'),[
'next_updated_at' = > 'updated_at',
'next_id' = > 'id',
]));
}
}
ReplacesQueryParameterNames.php
Mix in with the base Controller
.
<?php
detail( strict_types=1);
namespace App\Http\Controllers\Concerns;
/**
* Trait ReplacesQueryParameterNames
*/
trace ReplacesQueryParameterNames
{
/**
* Replace and return the key for the argument.
*
* @param array $input
* @param array $map
* @return array
*/
protected function replaceParameterNames(array$input,array$map)—array
{
$output=[];
foreach($input as$key=>$value){
$output[$map[$key]?? $key] = $value;
}
return$output;
}
}
© 2024 OneMinuteCode. All rights reserved.