yonka's avatar
Level 2

laravel livewire pagination links not working in where clause

    {
        return view('livewire.purchase.index',[
            'purchases' => Purchase::where('user_id',auth()->user()->id)->get(),
        ]);
    }

in the purchase.index

{{ $purchases->links() }}

But it shows this error Method Illuminate\Database\Eloquent\Collection::links does not exist.

0 likes
3 replies
LaryAI's avatar
Level 58

The error you're encountering is because you're trying to call the links() method on a collection, but pagination links are only available on a paginated instance, not a collection. To fix this, you need to use the paginate() method instead of get() when retrieving your data. Here's how you can modify your code:

{
    return view('livewire.purchase.index', [
        'purchases' => Purchase::where('user_id', auth()->user()->id)->paginate(10), // Adjust the number 10 to the number of items you want per page
    ]);
}

In your Blade view (purchase.index), you can then use:

{{ $purchases->links() }}

This will generate the pagination links correctly. The paginate() method returns a LengthAwarePaginator instance, which includes the links() method to render pagination controls. Adjust the number in paginate(10) to control how many items you want to display per page.

Snapey's avatar
return view('livewire.purchase.index')
        ->withPurchases(auth()->user()->purchases()->latest()->paginate(10));

Please or to participate in this conversation.