Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mishazapl
Created October 4, 2018 10:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishazapl/0450a6f7bce80144366fdf10bda92cd9 to your computer and use it in GitHub Desktop.
Save mishazapl/0450a6f7bce80144366fdf10bda92cd9 to your computer and use it in GitHub Desktop.
<?php
/**
* Created by PhpStorm.
* User: mihail
* Date: 15.08.18
* Time: 10:34
*/
namespace App\Services;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
class Pagination
{
/**
* @param Builder $builder
* @param int|null $perPage
* @param int $currentPage
* @param string $orderColumn
* @param string $sort
* @param string $select
* @param string $pageName
* @return LengthAwarePaginator
*/
public function ajax(
Builder $builder,
$perPage,
$currentPage,
$orderColumn,
$sort = 'DESC',
$select = '*',
string $pageName = 'page'
): LengthAwarePaginator
{
$model = $builder->getModel();
$fillable = $model->getFillable();
$select = $select == '*' ? ['*'] : array_only(explode(',',$select), array_flip($fillable));
$orderColumn = in_array($orderColumn, $fillable) ? $orderColumn : $fillable[0];
$sort = strtoupper($sort) == 'ASC' ? 'ASC' : 'DESC';
$select = collect($select)->reject(function ($name) {
return empty($name);
})->toArray();
return $builder->select((empty($select)) ? ['*'] : $select)
->orderBy($orderColumn, $sort)
->paginate((int)$perPage, ['*'], $pageName, $currentPage);
}
public function defaultQuery(Builder $builder): LengthAwarePaginator
{
return $this->ajax(
$builder,
request()->input('perPage'),
request()->input('page'),
request()->input('orderBy'),
request()->input('order'),
request()->input('select')
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment