When using Livewire, you can indeed take advantage of Laravel's built-in pagination features, even when using the DB facade. However, you need to manually create a paginator instance since the DB facade returns a Builder instance, not a Model or Eloquent\Builder instance which has the paginate method.
Here's how you can use the LengthAwarePaginator with the DB facade:
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Livewire\Component;
use Livewire\WithPagination;
class YourLivewireComponent extends Component
{
use WithPagination;
public function render()
{
$perPage = 10; // Number of items per page
$page = request()->page ?: 1; // Current page
$pageStart = ($page - 1) * $perPage; // Calculate the starting point
// Get the total number of records
$total = DB::table('services')->count();
// Retrieve the items for the current page
$services = DB::table('services')
->offset($pageStart)
->limit($perPage)
->get();
// Create a new LengthAwarePaginator instance
$paginator = new LengthAwarePaginator(
$services,
$total,
$perPage,
$page,
['path' => request()->url(), 'query' => request()->query()]
);
return view('livewire.your-view', [
'services' => $paginator
]);
}
}
In your Blade view, you can then render the pagination links as you would with Eloquent:
<div>
{{-- Your table or list here --}}
{{ $services->links() }}
</div>
This manual approach allows you to use the DB facade and still have pagination in your Livewire components. However, if you can use Eloquent models, it's generally simpler and more convenient, as you can just call the paginate method directly on the model query:
$services = Service::paginate(10);
And then in your Blade view:
<div>
{{-- Your table or list here --}}
{{ $services->links() }}
</div>
Using Eloquent also provides additional benefits, such as easier data manipulation and the ability to use relationships and other Eloquent features. If possible, prefer using Eloquent over the DB facade for these reasons.