Check data load more laravel livewire

how to check last data perPage and hide the button load more

class Index extends Component
{

    public $perPage = 12;

    public function loadMore()
    {
        $this->perPage = $this->perPage + 12;
    }

    public function render()
    {
        $products = Product::latest()->paginate($this->perPage);

        return view('livewire.frontend.home.index', [
            'products'  => $products
        ]);
    }
}

<button wire:click="loadMore()" class="btn btn-dark btn-lg shadow-sm">Load More</button>

So you need to add variables
public $hasMore = false;
public $currentPage = 0;

In template you would need to have something like this:

@if($hasMore)
    @livewire('livewire.frontend.home.index', ['page' => $currentPage + 1])
@else
   <button wire:click="loadMore()" class="btn btn-dark btn-lg shadow-sm">Load More</button>`
@endif

And you need a mount method to apply page to currentPage variable.

1 Like

@Dimonka2 thanks bro, but the mount function like what ?

    public function mount($page)
    {
        $this->currentPage = $page;
    }

And then in the render function do not use paginate(). Use something like:

Product::latest()->offset($this->currentPage * $this->perPage)->limit($this->perPage)->get();
1 Like

@Dimonka2, im get the error about mount function to get the $page, like the screenshot

I see. Make then the following in mount declaration:

public function mount($page = 0)    
1 Like

@Dimonka2 work and no problem bro, but the button still there :grinning:

That is correct. You need to change hasMore variable yourself :slight_smile:

    public function loadMore()
    {
        $this->hasMore= true;
    }
1 Like

Ah and of cause you also need to think about a case when there is no “more”.

1 Like

this is my problem bro @Dimonka2

Count number of $products in render function and render “No more products” view in case of zero :wink:

1 Like

thanks very much bro @Dimonka2 :wink: :love_you_gesture:

Since $products is paginated, there should be Pagination accessor that will let you check if there are more pages.

In your blade component where you want the load more button to appear, you can use:

@if($products->hasMorePages())
    <button wire:click="loadMore()" class="btn btn-dark btn-lg shadow-sm">Load More</button>
@endif

There’s another topic where this is covered: Implement Load More Pagination if you need additional information or want to see a working example.

1 Like