Laravel provides built-in pagination for Eloquent results, but for custom data like arrays, manual pagination is needed. In this tutorial, we'll explore how to use Laravel's `LengthAwarePaginator` class to create a paginated list of results from an array of data.
Step 1: Create Controller
Create a new controller named `ItemsController` in the `app/Http/Controllers` directory. Place the following code in `ItemsController.php`:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Pagination\LengthAwarePaginator;
class ItemsController extends Controller
{
public function items(Request $request)
{
$items = [
'item1', 'item2', 'item3', 'item4', 'item5',
'item6', 'item7', 'item8', 'item9', 'item10'
];
$currentPage = LengthAwarePaginator::resolveCurrentPage();
$itemCollection = collect($items);
$perPage = 1;
$currentPageItems = $itemCollection
->slice(($currentPage * $perPage) - $perPage, $perPage)
->all();
$paginatedItems = new LengthAwarePaginator(
$currentPageItems,
count($itemCollection),
$perPage
);
$paginatedItems->setPath($request->url());
return view('items_view', ['items' => $paginatedItems]);
}
}
Step 2: Create View
Create a Blade view named `items_view.blade.php` in the `resources/views` directory. Place the following code in the view:
<h1>Items List</h1>
<ul>
@foreach ($items as $item)
<li>{{ $item }}</li>
@endforeach
</ul>
<div>{{ $items->links() }}</div>
Step 3: Define Route
Define a route to access the `items` method of the `ItemsController`. Open the `routes/web.php` file and add the following route:
Route::get('items', 'ItemsController@items');
Conclusion
In this tutorial, you've learned how to manually paginate an array of data using Laravel's `LengthAwarePaginator` class. By following the steps provided, you can create a paginated list of results from custom data and display it in your Laravel application.
We hope this tutorial helps you understand how to achieve pagination with array data in Laravel!
Feel free to customize the code according to your project's needs and add more features to enhance the user experience.
0 Comments