Divide Your Posts with Laravel Livewire Pagination

Hello Artisan

Laravel Livewire offers the ability to paginate results within a component. This feature hooks into Laravel's native pagination features, so it should feel like an invisible feature to you.

This post is going to focus laravel livewire pagination example. In this quick example i will discuss about laravel 8 livewire pagination tutorial. We will create livewire pagination so that we can go next page without reloading the current page.

We can do it using Ajax, Vue or React. But in this example we will create same staff using Livewire packages. It will give us very light weight pagination system in our application. 

So to create a Livewire pagination, see the below example code. Think you have a show-posts component, but you want to limit the results to 10 posts per page. We can easily paginate the results by using the WithPagination trait provided by Livewire.

use Livewire\WithPagination;

class ShowPosts extends Component
{
    use WithPagination;

    public function render()
    {
        return view('livewire.show-posts', [
            'posts' => Post::paginate(10),
        ]);
    }
}

 

And in you view 

@foreach ($posts as $post)
        ...

@endforeach

{{ $posts->links() }}

 

Now there will be rendered HTML links for the different pages for our posts at the bottom of our posts, and the results will be paginated.

Resetting Pagination After Filtering Data

A common pattern when filtering a paginated result set is to reset the current page to "1" when filtering is applied. 

Just think as an example, If a user visits page "4" of your data set, then types into a search field to narrow the results, it is usually desireable to reset the page to "1".

Livewire's WithPagination trait exposes a ->resetPage() method to accomplish this problem. 

This method can be used in combination with the updating/updated lifecycle hooks to reset the page when certain component data is updated in Livewire.

use Livewire\WithPagination;

class ShowPosts extends Component
{
    use WithPagination;

    public $search = '';

    public function updatingSearch()
    {
        $this->resetPage();
    }

    public function render()
    {
        return view('livewire.show-posts', [
            'posts' => Post::where('title', 'like', '%'.$this->search.'%')->paginate(10),
        ]);
    }
}

 

Bootstrap Pagination Theme

You know that like Laravel, Livewire's default pagination view uses Tailwind classes for styling. But If you use Bootstrap in your application, you can enable the Bootstrap theme for the pagination view using the $paginationTheme property on your component and you have nothing to do.

class ShowPosts extends Component
{
    use WithPagination;

    protected $paginationTheme = 'bootstrap';

}

 

Recommended : Complete Beginners Guide on Laravel Livewire Events

 

You can read this official docs to know more about livewire pagination.