Skip to content

Instantly share code, notes, and snippets.

@kkiernan
Last active June 6, 2023 07:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save kkiernan/176cce9ca80865c23a97 to your computer and use it in GitHub Desktop.
Save kkiernan/176cce9ca80865c23a97 to your computer and use it in GitHub Desktop.
A reusable helper class for pagination of array items in Laravel.
<?php
namespace App\Http\Utilities;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Collection;
class ArrayPaginator
{
/**
* @var \Illuminate\Http\Request
*/
protected $request;
/**
* Creates a new array paginator instance.
*
* @param \Illuminate\Http\Request $request
*/
public function __construct(Request $request)
{
$this->request = $request;
}
/**
* Paginates an array of items.
*
* @param mixed $items
* @param integer $length
* @param string $path (optional)
*
* @return \Illuminate\Pagination\LengthAwarePaginator
*/
public function paginate($items, $length = 10, $path = null)
{
if ($items instanceof Collection) {
$items = $items->all();
}
$page = $this->request->get('page') ?: 1;
$offset = ($page - 1) * $length;
$paginator = new LengthAwarePaginator(array_slice($items, $offset, $length), count($items), $length);
if ($path) {
$paginator->setPath($path);
} else {
$paginator->setPath($this->request->path());
}
return $paginator;
}
}
<?php
namespace App\Http\Controllers;
use App\Http\Utilities\ArrayPaginator;
use Illuminate\Support\Facades\DB;
class ControllerExample extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\View\View
*/
public function index(ArrayPaginator $paginator)
{
$users = $paginator->paginate(['Your', 'Array', 'Or', 'Collection', 'Here'], 2);
return view('users.index', compact('users'));
}
}
<h1>Users</h1>
@foreach ($users as $user)
<p>{{ $user->name }} - {{ $user->email }}</p>
@endforeach
{{-- Render the pagination links... --}}
{!! $users->render() !!}
{{-- Or you can use... --}}
{!! $users->links() !!}
{{-- You can even pass in a custom presenter if you have one... --}}
{!! $users->links(new \App\Presenters\BootstrapFourPresenter($users)) !!}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment