Created
October 4, 2018 10:15
-
-
Save mishazapl/0450a6f7bce80144366fdf10bda92cd9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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