Created
February 22, 2019 00:45
-
-
Save wanmigs/14d6582169d0dbbf7ce48303437d117c to your computer and use it in GitHub Desktop.
Laravel Pagination + Filter
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 | |
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