DEV Community

Agik Setiawan
Agik Setiawan

Posted on

Use Pure Datatable in Laravel Livewire with AlpineJS

Datatable is most popular Jquery plugin for make table easy with simple code.

<div x-data="app()" x-init="init()">
    <table class="table table-bordered" id="tableExample">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
</div>

<script>
    function app() {
        return {
            dataTable(newData = "") {
                const data = newData !== '' ? newData : {!! json_encode($users) !!};
                $('#tableExample').DataTable({
                    data: data,
                    columns: [
                        {
                            data: 'name'
                        },
                        {
                            data: 'email'
                        },
                    ],
                    destroy: true,
                    language: {
                        searchPlaceholder: 'Search...',
                        scrollX: "100%",
                        sSearch: '',
                    }
                });
            },
            init() {
                const _this = this;
                _this.dataTable();
                Livewire.on("dataChanged", function(data) {
                    _this.dataTable(data);
                });
            }
        }
    }
</script>
Enter fullscreen mode Exit fullscreen mode

you can changed new data from livewire function event with dataChanged function for retreive new data.

Top comments (0)