Laravel pagination on array

718 0 0 0

Last Updated : 2024-04-25 23:52:06

In case you have an array and would like to create pagination over it here is a user sample code.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
use Illuminate\Pagination\LengthAwarePaginator;

class PaginationController extends Controller
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
public function index()
{
$myArray = [
['id'=>1, 'title'=>'Laravel CRUD'],
['id'=>2, 'title'=>'Laravel Ajax CRUD'],
['id'=>3, 'title'=>'Laravel CORS Middleware'],
['id'=>4, 'title'=>'Laravel Autocomplete'],
['id'=>5, 'title'=>'Laravel Image Upload'],
['id'=>6, 'title'=>'Laravel Ajax Request'],
['id'=>7, 'title'=>'Laravel Multiple Image Upload'],
['id'=>8, 'title'=>'Laravel Ckeditor'],
['id'=>9, 'title'=>'Laravel Rest API'],
['id'=>10, 'title'=>'Laravel Pagination'],
];

$data = $this->paginate($myArray);

return view('paginate', compact('data'));
}

/**
* The attributes that are mass assignable.
*
* @var array
*/
public function paginate($items, $perPage = 5, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
}

In your view :


<div class="container">
<table class="table table-bordered">
<tr>
<th>Id</th>
<th>Title</th>
</tr>
@foreach($data as $post)
<tr>
<td>{{ $post->id }}</td>
<td>{{ $post->title }}</td>
</tr>
@endforeach
</table>
</div>

{{ $data->links() }}

-

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .