Pagination not working on a Livewire Property?

When working with Laravel and Livewire, you might encounter an issue where default pagination doesn't work as expected. This often happens when a variable is declared as a public property. Let's dive into why this occurs and how to resolve it.

The Problem

Stack Context Debug Share
Docs

Livewire \ Exceptions \ PublicPropertyTypeNotAllowedException

Livewire component's [UsersTable] public property [users] must be of type: [numeric, string, array, null, or boolean]. Only protected or private properties can be set as other types because JavaScript doesn't need to access them.

PHP 8.2.0 10.0.0

In Livewire, public properties are automatically available to the view. However, when it comes to pagination, declaring the pagination variable as a public property can lead to unexpected behavior like the one above. This is because Livewire's reactivity system doesn't handle pagination state changes correctly when the variable is public.

The Solution

To ensure pagination works correctly, you should pass the pagination variable directly when calling the Livewire view. Here's how you can do it:

1. Remove the Public Property

First, ensure that the pagination variable is not declared as a public property in your Livewire component.

class UsersTable extends Component
{
    // Remove public $users;
    
    public function render()
    {
        $users = User::paginate(10); // or whatever query you have
        return view('livewire.users-table', ['users' => $users]);
    }
}

2. Pass the Variable to the View

Instead of relying on a public property, pass the pagination variable directly to the view in the render method.

public function render()
{
    $users = User::paginate(10);
    return view('livewire.users-table', ['users' => $users]);
}

3. The View

In your Livewire view, you can now use the passed variable without any issues.

<div>
    
  <table>

  @foreach($users as $user)

    <!-- Table Rows -->

  @endforeach

  </table>

  {{ $users->links() }}

</div>

Handling pagination in Laravel with Livewire requires careful management of state. Avoid using public properties for pagination variables and instead pass them directly to the view.

Feel free to reach out if you have any questions or need further assistance with Livewire and Laravel!