Laravel

Livewire Data Tables Pattern

January 16, 2026 1 min read 21 views

Data table component:

Component

class UsersTable extends Component
{
    #[Url]
    public $search = '';
    
    #[Url]
    public $sortBy = 'name';
    
    #[Url]
    public $sortDir = 'asc';

    public function sort($column)
    {
        if ($this->sortBy === $column) {
            $this->sortDir = $this->sortDir === 'asc' ? 'desc' : 'asc';
        } else {
            $this->sortBy = $column;
            $this->sortDir = 'asc';
        }
    }
}

Query

#[Computed]
public function users()
{
    return User::query()
        ->when($this->search, fn($q) => $q->where('name', 'like', "%{$this->search}%"))
        ->orderBy($this->sortBy, $this->sortDir)
        ->paginate(10);
}
Share this post:

Related Posts

Comments (0)

Please log in to leave a comment. Log in

No comments yet. Be the first to comment!