To make the ->paginate() method in Laravel generate relative URLs instead of absolute URLs, you can use the Paginator::useBootstrap() method to customize the URL generation. However, Laravel's paginator by default generates absolute URLs. To achieve relative URLs, you can modify the URL generation logic by using a custom paginator view or by overriding the URL generation method.
Here's a simple way to achieve this by overriding the URL generation:
-
Create a Custom Paginator View:
First, you need to publish the pagination views so you can customize them:
php artisan vendor:publish --tag=laravel-paginationThis will copy the pagination views to
resources/views/vendor/pagination. -
Modify the Pagination View:
Open the pagination view file you want to modify, for example,
resources/views/vendor/pagination/bootstrap-4.blade.php. -
Customize the URL Generation:
In the pagination view, you can modify the URL generation logic. Replace the
urlmethod with a custom function that generates relative URLs. For example:@if ($paginator->hasPages()) <ul class="pagination" role="navigation"> {{-- 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">‹</span> </li> @else <li class="page-item"> <a class="page-link" href="{{ request()->url() . '?page=' . ($paginator->currentPage() - 1) }}" rel="prev" aria-label="@lang('pagination.previous')">‹</a> </li> @endif {{-- 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()) <li class="page-item active" aria-current="page"><span class="page-link">{{ $page }}</span></li> @else <li class="page-item"><a class="page-link" href="{{ request()->url() . '?page=' . $page }}">{{ $page }}</a></li> @endif @endforeach @endif @endforeach {{-- Next Page Link --}} @if ($paginator->hasMorePages()) <li class="page-item"> <a class="page-link" href="{{ request()->url() . '?page=' . ($paginator->currentPage() + 1) }}" rel="next" aria-label="@lang('pagination.next')">›</a> </li> @else <li class="page-item disabled" aria-disabled="true" aria-label="@lang('pagination.next')"> <span class="page-link" aria-hidden="true">›</span> </li> @endif </ul> @endifIn this example,
request()->url()is used to get the current URL without the query string, and then'?page=' . $pageis appended to create a relative URL.
By following these steps, you can customize the pagination links to use relative URLs in your Laravel application.