laravel livewire pagination with a collection
Hi , how can i use livewire pagination with the following user collection
my component:
$this->users = User::with('roles','permissions')->get();
return view('livewire.permission.user_permissions',[$this->permissions,$this->roles, $this->users])
Paginate is not accepting with collection.. showing error
When using WithPagination Livewire expects a Paginator instance.
Try this:
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Illuminate\Pagination\LengthAwarePaginator;
use Livewire\Component;
use Livewire\WithPagination;
class PaginatorExample extends Component
{
use WithPagination;
public function render()
{
$perPage = 10;
$collection = User::all();
$items = $collection->forPage($this->page, $perPage);
$paginator = new LengthAwarePaginator($items, $collection->count(), $perPage, $this->page);
return view('livewire.paginator-example', ['users' => $paginator]);
}
}
If you want to use simple pagination (no direct page links), you can try:
<?php
namespace App\Http\Livewire;
use App\Models\User;
use Illuminate\Pagination\Paginator;
use Livewire\Component;
use Livewire\WithPagination;
class PaginatorExample extends Component
{
use WithPagination;
public function render()
{
$perPage = 10;
$collection = User::all();
$offset = max(0, ($this->page - 1) * $perPage);
// need one more here so the simple paginatior knows
// if there are more pages left
$items = $collection->slice($offset, $perPage + 1);
$paginator = new Paginator($items, $perPage, $this->page);
return view('livewire.paginator-example', ['users' => $paginator]);
}
}
Component template:
<div>
<ul>
@foreach($users as $user)
<li>{{ $user->name }}</li>
@endforeach
</ul>
{{ $users->links() }}
</div>
Hope this helps.
@rodrigo.pedra Thanks for posting this code sample and solution. I was running into an issue with pagination with a collection and this post came up in my search and helped me fix my problem. You solved me hours of work tonight. Thanks for your community help and sharing your knowledge! -Donnell
@donnell.wyche glad to help =) Thanks for your kind words
Thank u for the reply.. i have corrected it. The issue in may code was the collection variable was public. I have changed it to local and passed to view. It is working fine now. Thank u very much. However I will try with your code example
public function render()
{
return view('livewire.transaction-history' , [ 'transaction' => Transaction::with(['cashier', 'payments'])->paginate(4) ]);
}
Please or to participate in this conversation.