Paginate in Laravel Livewire Volt using the anonymous class

Aug 2023

When using Laravel Livewire Volt, you can't simply use typical pagination (in the render() function) because the render() function is reserved by Volt.

As of this writing, the docs cover how to paginate data using the API-based style, but not the class-based style.

Here's how to do it...

Livewire 3 adds computed properties, so I was able to paginate my results with a full-page Volt component like this:


use App\Models\Post;
use Illuminate\Database\Eloquent\Collection;
use Livewire\Attributes\Computed;
use Livewire\Volt\Component;
use Livewire\WithPagination;

new class extends Component {

    use WithPagination;

    #[Computed]
    public function posts()
    {
        return Post::paginate(10);
    }
    
}

and then in the HTML/Blade, I did this:

@foreach($this->posts as $post)
...
@endforeach

{{ $this->posts->links() }}

The Livewire 3 docs on computed properties explain more about how Computed Properties work.

At first, I didn't know I needed to import use Livewire\Attributes\Computed;. As a result, it threw an error when I tried to do $this->posts, so make sure to add that import.

I hope that helps!