Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,9 @@ Default methods of the `Kurt\Repoist\Repositories\Eloquent\AbstractRepository`.
| **update** | $repo->update($id, array $properties);
| **delete** | $repo->delete($id);

Comes with a integrated pagination functions that uses `Illuminate\Pagination\LengthAwarePaginator` to
return a paginated response if $request->limit > 0

## Example Usage

Customer.php
Expand Down
40 changes: 37 additions & 3 deletions src/Repositories/Eloquent/AbstractRepository.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
namespace Kurt\Repoist\Repositories\Eloquent;

use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Pagination\LengthAwarePaginator;
use Kurt\Repoist\Exceptions\NoEntityDefined;
use Kurt\Repoist\Repositories\Contracts\RepositoryInterface;
use Kurt\Repoist\Repositories\Criteria\CriteriaInterface;
use Illuminate\Http\Request;

abstract class AbstractRepository implements RepositoryInterface, CriteriaInterface
{
Expand All @@ -14,9 +16,16 @@ abstract class AbstractRepository implements RepositoryInterface, CriteriaInterf
*/
protected $entity;

public function __construct()
/**
* @var Illuminate\Http\Request
*/
protected $request;


public function __construct(Request $request)
{
$this->entity = $this->resolveEntity();
$this->request = $request; // reading request here allows many options.
}

/**
Expand Down Expand Up @@ -99,7 +108,7 @@ public function findWhereLike($columns, $value, $paginate = null)
*/
public function paginate($perPage = 10)
{
return $this->entity->paginate($perPage);
return $this->processPagination($this->entity, $perPage);
}

/**
Expand Down Expand Up @@ -156,6 +165,31 @@ protected function resolveEntity()

private function processPagination($query, $paginate)
{
return $paginate ? $query->paginate($paginate) : $query->get();
return $this->paginateIf($query>get(), $paginate);
}

private function paginateIf($records, $per_page)
{

if ($per_page>0) {
// We can bypass and continue...
} elseif ($this->request->input('limit') > 0){
// $per_page=null, but we could try find "limit" form request
$per_page = $this->request->input('limit');
} else {
return $records;
}

$page = $this->request->input('page') > 0 ? $this->request->input('page') : 1;
$offset = ($page * $per_page) - $per_page;

return new LengthAwarePaginator(
array_slice($records->toArray(), $offset, $per_page, true),
$records->count(),
$per_page,
$page,
['path' => $this->request->url(), 'query' => $this->request->query()]
);

}
}