Laravel Livewire infinite scroll

Solved
succute

Jan 11th, 2021 09:55 AM

How to create a Laravel Livewire infinite scrolling?

bobbyiliev

Jan 11th, 2021 10:26 AM

Best Answer

Hi there,

What you could do is follow the steps here:

  • First in your Component Class add a listener:
    protected $listeners = [
        'load-more' => 'loadMore',
    ];
  • After that add a public property which will be used to specify how many entries to be loaded:
    public $numResults = 20;
  • Then in your render method define your pagination as normal but inlcude the numResults proeprty:
    public function render()
    {
        $posts = Post::query()
                            ->where('status', 'active')
                            ->orderBy('created_at', 'desc')
                            ->paginate($this->numResults);
        return view('livewire.posts', compact('posts'));
    }
  • Finally include the following JavaScript to detect when more posts have to be loaded:
<script type="text/javascript">
    window.onscroll = function(ev) {
        if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
            window.livewire.emit('load-more');
        }
    };
</script>
  • Finally in your view add a foreach method as usual

You can take a look at the following project as an example:

https://github.com/guildso/guild/blob/main/resources/views/livewire/posts.blade.php

https://github.com/guildso/guild/blob/main/app/Http/Livewire/Posts.php

Hope that this helps! Regards, Bobby

Report
4