laravelpagination

Laravel pagination - How to hide next button at the end


Using Laravel's pagination. It is working but when it gets to the last page it shows both the previous and next button. Is there a way to hid the "next" button?

public function index() {
     
       $posts = Post::orderBy('created_at', 'desc')->paginate(10);
       return view('posts.index', compact('posts'));
    }

  
 @foreach ($posts as $post) 
  {{$post->title}}
 @endforeach
 {!! $posts->links() !!} 

{{ $posts->onEachSide(2)->links() }}

Solution

  • Yes, you can hide the "next" button on the last page in Laravel pagination by customizing the pagination links. Laravel's default pagination views provide a way to conditionally display the next and previous buttons. You can create a custom pagination view and modify it to hide the "next" button on the last page.

    1. First, publish the pagination views to your resources/views/vendor directory.
    2. Modify the Pagination View Open the resources/views/vendor/pagination/default.blade.php file (or another view file if you're using a different style).

    Locate the section that renders the "Next" button and add a condition to check if it's the last page. 3. Use the Custom Pagination View {!! $posts->links('vendor.pagination.default') !!}