I didn't get it but Laravel already has Pagination method.
Nov 30, 2019
4
Level 75
Paginate collection simple example (Guide)
Another question also recently came up on the length aware paginator usage.
in controller add at top
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;
A controller method just to test:
public function colPaginate()
{
$page = !empty(Request::input('page')) ? Request::input('page') : '1';
$perPage = "1";
$offset = ($page - 1) * $perPage;
//$current_page = LengthAwarePaginator::resolveCurrentPage();
$current_page = $page;
$employees = collect([
['id' => 4, 'email' => '[email protected]', 'position' => 'Developer'],
['id' => 7, 'email' => '[email protected]', 'position' => 'Designer'],
['id' => 9, 'email' => '[email protected]', 'position' => 'Developer'],
['id' => 2, 'email' => '[email protected]', 'position' => 'boss'],
]);
$current_page_employees = $employees->slice($offset, $perPage)->all();
$employee = new LengthAwarePaginator($current_page_employees, count($employees), $perPage);
return view('testarray.pagcol')
->with('employee', $employee);
}
Just a quick test view:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="{{ asset('js/app.js') }}" defer></script>
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
</head>
<body>
@foreach ($employee as $r)
{{ $r['id'] }} | {{ $r['email'] }} | {{ $r['position'] }} </br>
@endforeach
@php echo str_replace('/?', '?', $employee->links('pn')); @endphp
</body>
</html>
This line:
@php echo str_replace('/?', '?', $employee->links('pn')); @endphp
The pn is a custom previous next only display. If wanting regular links, then:
@php echo str_replace('/?', '?', $employee->links()); @endphp
If you want just previous and next add this code in a file in the view folder, name it pn.blade.php
@if ($paginator->hasPages())
<nav>
<ul class="pagination">
{{-- Previous Page Link --}}
@if ($paginator->onFirstPage())
<li class="page-item disabled" aria-disabled="true">
<span class="page-link">@lang('pagination.previous')</span>
</li>
@else
<li class="page-item">
<a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">@lang('pagination.previous')</a>
</li>
@endif
{{-- Next Page Link --}}
@if ($paginator->hasMorePages())
<li class="page-item">
<a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">@lang('pagination.next')</a>
</li>
@else
<li class="page-item disabled" aria-disabled="true">
<span class="page-link">@lang('pagination.next')</span>
</li>
@endif
</ul>
</nav>
@endif
Gives next and previous.
Restyle links as you wish.
Note on style, you have to change the style as needed if using other than bootstrap. Lines such as:
<li class="page-item">
As laravel comes with several different pagination templates. Some of which is meant to use with bootstrap.
Also there's https://gist.github.com/vluzrmos/3ce756322702331fdf2bf414fea27bcb
For lengthaware example.
Please or to participate in this conversation.