How to set up pagination in Laravel 10
You can use the Paginator
class provided by Laravel to handle the pagination functionality.
Here's an example of how you can achieve this:
// In your controller
public function index()
{
$data = YourModel::paginate(12);
if ($data->total() > 12) {
return view('your-view', ['data' => $data]);
} else {
return view('your-view', ['data' => $data->items()]);
}
}
In the above code, we're using the paginate() method to fetch the data, and then checking the total number of items. If the total is greater than 12, we pass the entire $data object to the view, which will automatically generate the pagination links. If the total is less than or equal to 12, we pass only the $data->items() to the view, which will not display any pagination links.
In your view, you can use the @if directive to conditionally display the pagination links:
<table>
<!-- Display your data here -->
</table>
@if ($data->hasPages())
<div class="pagination">
{{ $data->links() }}
</div>
@endif
The $data->hasPages() check will ensure that the pagination is only displayed if there are more than 12 items.
If you want to customize the appearance of the pagination links, you can publish the pagination views and modify them:
php artisan vendor:publish --tag=laravel-pagination
This will create a resources/views/vendor/pagination directory, where you can find the default pagination views and customize them to fit your needs.