Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Magalliu's avatar

Redirect to current page or to 1st page when pagination is empty

So I want to redirect back to current page or to page 1 in case that the pagination does not exist so I can avoid that laravel can return empty string.

I'm a litt blocked here cause I don't have any solution in my mind how can I manage this in blade or elsewhere.

Any suggestion how to achieve this?

Thanks!

0 likes
12 replies
jlrdw's avatar

Laravel out of the box pagination handles this already.

Magalliu's avatar

I know what you mean but the situation is that I got an input from which i can change the page manually, and when I change to some non existing page it returns the page content empty, so practically and empty string.

jlrdw's avatar

Use a length aware paginator.

Magalliu's avatar

Not used before and I have to dig in to understand how does it work. Anyway thanks for the suggestion.

Magalliu's avatar

Thanks it will be helpful in this situation and I think is the time to learn it once for all.

newbie360's avatar

Customizing The Pagination View

https://laravel.com/docs/7.x/pagination#customizing-the-pagination-view

php artisan vendor:publish --tag=laravel-pagination

edit resources\views\vendor\pagination\simple-bootstrap-4.blade.php

@if ($paginator->hasPages())
    <div>
        <nav>
            <ul class="pagination">
                {{-- Previous Page Link --}}
                @if ($paginator->onFirstPage())
                    <li class="page-item disabled" aria-disabled="true">
                        <span class="page-link">@lang('pagination.previous')</span>
                    </li>
                @else
                    <li class="page-item">
                        <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev">@lang('pagination.previous')</a>
                    </li>
                @endif

                {{-- Next Page Link --}}
                @if ($paginator->hasMorePages())
                    <li class="page-item">
                        <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next">@lang('pagination.next')</a>
                    </li>
                @else
                    <li class="page-item disabled" aria-disabled="true">
                        <span class="page-link">@lang('pagination.next')</span>
                    </li>
                @endif
            </ul>
        </nav>
    </div>



    {{-- add this inputbox --}}
    <div class="pl-2">
        <div class="input-group">
            <input type="text" class="form-control jump-to-page" placeholder="{{ $paginator->currentPage() }}">
            <div class="input-group-append">
                <span class="input-group-text">/ {{ $totalPage }} @lang('pagination.page')</span>
            </div>
        </div>
    </div>
@endif

@once
    @push('master-script')
        // push this code to your master layout
        <script>
        // jump-to-page
        $(".jump-to-page").keydown(function(event){
            if (event.which == 13){
                var page = parseInt(this.value);

                if (page >= 1 && page <= {{ $totalPage }}) {
                    window.location.href='{{ implode("?", $paginator->getOptions()) }}='+page;
                }
            }
        });
        </script>
    @endpush
@endonce

add lang -- resources\lang\en\pagination.php

    'previous' => '&laquo; Previous',
    'next' => 'Next &raquo;',
    'page' => 'Page',

add css

.jump-to-page {
    width: 80px !important;
    height: calc(1.5em + .75rem + 1px);
}

Controller

$posts = Post::select('id','name')->simplePaginate(50);
$postsCount = Post::count();
$totalPage = ceil($postsCount / 50);
return view('posts.index', compact('posts', 'postsCount', 'totalPage'));

View:

// you can create a component for this too
{{ $posts->links('vendor.pagination.simple-bootstrap-4', ['totalPage' => $totalPage]) }}

now the inputbox only take action when you type a number(must be >=1 and <= totalPage) and hit enter will jump to that page

it will look like this

jump-to-page

1 like
Magalliu's avatar

Thanks @newbie360, I had the idea of achieving that using javascript but I wanted a solution in Laravel's way but this will handle my problem for the moment.

newbie360's avatar

be careful in my example is no query condition such where()

so if there has ->where(), the $totalPage is wrong number, in the case, you may need calc by youself

$query = Post::query();
$query->select(
    'id',
    'title',
)
->where('id', '>', 10);

$postsCount = $query->count(); // need to get the real total
$posts = $query->simplePaginate(50);
$totalPage = ceil($postsCount / 50);
return view('posts.index', compact('posts', 'postsCount', 'totalPage'));

if use ->paginate(50) is more easy, because that provide $paginator->lastPage()

1 like
Magalliu's avatar
Magalliu
OP
Best Answer
Level 2

I'm going to give another answer based on @newbie360 answer.

  • As per Laravel 8 all you need to do is to export paginations views under resources/views using:
php artisan vendor:publish --tag=laravel-pagination
  • After that the default pagination blade file as per laravel 8 is bootstrap-4.blade.php and on that view you can just do this:
@if ($paginator->hasPages())
    <nav aria-label="Page navigation" class="page-navigation">
        <span class="pagination-label">{{ __('pagination.page') }}</span>

        {{-- Pagination Elements --}}
            @foreach ($elements as $element)
                {{-- "Three Dots" Separator --}}
                @if (is_string($element))
                    <li class="page-item disabled" aria-disabled="true"><span class="page-link">{{ $element }}</span></li>
                @endif

                {{-- Array Of Links --}}
                @if (is_array($element))
                    @foreach ($element as $page => $url)
                        @if ($page == $paginator->currentPage())
                        <form>
                            <div class="form-group">
                            <label for="page_number" class="sr-only">{{ __('pagination.page') }}</label>
                            <input
                                type="number"
                                class="form-control jump-to-page"
                                id="page_number"
                                name="page"
                                aria-describedby="pageNumber"
                                value="{{$page}}"
                                pattern="^[0-9]"
                                oninput="validity.valid||(value='')"
                                min="1"
                                step="1"
                            />
                            </div>
                        </form>
                        @endif
                        
                        
                    @endforeach
                    <span class="pagination-total">{{ __('pagination.of') }} {{ $page }}</span>
                @endif
            @endforeach

        <ul class="pagination">
            {{-- Previous Page Link --}}
            @if ($paginator->onFirstPage())
                <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.previous')">
                    <span class="page-link" aria-hidden="true"><i aria-hidden="true" class="fas fa-chevron-left"></i></span>
                </li>
            @else
                <li class="page-item">
                    <a class="page-link" href="{{ $paginator->previousPageUrl() }}" rel="prev" aria-label="@lang('pagination.previous')"><i aria-hidden="true" class="fas fa-chevron-left"></i></a>
                </li>
            @endif

            

            {{-- Next Page Link --}}
            @if ($paginator->hasMorePages())
                <li class="page-item">
                    <a class="page-link" href="{{ $paginator->nextPageUrl() }}" rel="next" aria-label="@lang('pagination.next')"><i aria-hidden="true" class="fas fa-chevron-right"></i></a>
                </li>
            @else
                <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.next')">
                    <span class="page-link" aria-hidden="true"><i aria-hidden="true" class="fas fa-chevron-right"></i></span>
                </li>
            @endif
        </ul>
    </nav>
@endif

@if ($paginator->hasPages())
    @once
        @push('frontend.layouts.footer-scripts')
        <script>
            // jump-to-page
            $(".jump-to-page").keydown(function(event){
                if (event.which == 13){
                    var page = parseInt(this.value);

                    if (page >= 1 && page <= {{ $page }}) {
                        window.location.href='{{ implode("?", $paginator->getOptions()) }}='+page;
                    } else {
                        event.preventDefault();
                    }
                }
            });
            </script>
        @endpush
    @endonce
@endif

As you can see I added event.preventDefault(); to prevent keydown in case that page number does not exist:

else {
       event.preventDefault();
}
  • Your controller could be simple as this:
 public function categoryProducts($locale, $slug)
    {
        // dd($slug);

        $category = Category::findOrFail($slug);

        $products = Product::where('category_id', '=', $category->id)->paginate(9);

        return view('frontend.pages.category_products', compact('category','products'));
    }

Thanks again, I hope it can help someone!

1 like
newbie360's avatar

cool

yes, if use ->paginate() instead of ->simplePaginate() is more easy

1 like

Please or to participate in this conversation.