How to set up pagination in Laravel 10 ?

Aug 05, 2024 5 mins read

How to set up pagination in Laravel 10

  1. Show "Next Page" option only if there are more than 12 data items.
  2. Do not show the pagination if there are less than or equal to 12 data items.

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.

Image NewsLetter
Icon primary
Newsletter

Subscribe our newsletter

By clicking the button, you are agreeing with our Term & Conditions