Skip to content

Instantly share code, notes, and snippets.

@wanmigs
Created February 22, 2019 00:45
Show Gist options
  • Save wanmigs/14d6582169d0dbbf7ce48303437d117c to your computer and use it in GitHub Desktop.
Save wanmigs/14d6582169d0dbbf7ce48303437d117c to your computer and use it in GitHub Desktop.
Laravel Pagination + Filter
<?php
namespace App\Traits;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
trait Paginators
{
private $sortBy = ['created_at' => 'desc'];
public function paginate($builder, $attributes = [])
{
$limit = request('limit', 10);
$offset = request('offset', 0);
$sort = request('sort', null);
$order = request('order', null);
$keyword = request('keyword', '');
$currentPage = ($offset / $limit) + 1;
Paginator::currentPageResolver(function () use ($currentPage) {
return $currentPage;
});
$builder->when($keyword && $attributes, function ($query) use ($attributes, $keyword) {
foreach (array_wrap($attributes) as $attribute) {
$query->when($attributes, function ($query) use ($attribute, $keyword) {
return $query->orWhere($attribute, 'LIKE', "%{$keyword}%");
});
}
});
$builder->when(!$sort, function ($query) {
foreach (array_wrap($this->sortBy) as $sort => $order ) {
return $query->orderBy($sort, $order);
}
});
return $builder->when($sort, function ($query) use ($sort, $order) {
return $query->orderBy($sort, $order);
})->paginate($limit);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment