shutterstock 1142996930

How to Implement Data Tables Using Livewire?

This guide will let you understand how you can implement data tables using livewire framework.

Livewire is full PHP based full stack framework which is included in Laravel to create dynamic webpages without learning Vue or React. Livewire actually sends AJAX based requests on runtime without using any AJAX script. It is fully PHP based. This means we do not need to write even a word of JavaScript and we can implement DataTables which will not require page loading. Isn’t it amazing? In order to do so, we first need a fresh Laravel installation. After that please install Livewire.

composer require livewire/livewire

Then we will install mediconesystems/livewire-datatables package using this command.

composer require mediconesystems/livewire-datatables

Then we need to make a new livewire component using this php artisan command.

php artisan livewire:datatable users-table --model=user

This will generate a new Livewire component called app/Http/Livewire/UsersTable.php and we will write this code in our component.

namespace App\Http\Livewire;

use App\Models\User;
use Mediconesystems\LivewireDatatables\Http\Livewire\LivewireDatatable;
use Mediconesystems\LivewireDatatables\Column;
use Mediconesystems\LivewireDatatables\NumberColumn;
use Mediconesystems\LivewireDatatables\DateColumn;

class UsersTable extends LivewireDatatable
{
    public $model = User::class;

    public function columns()
    {
        return [
            NumberColumn::name('id')
                ->label('ID')
                ->defaultSort('asc')
                ->sortBy('id'),

            Column::name('name')
                ->label('Name'),

            Column::name('email')
                ->label('Email'),

            Column::name('phone')
                ->label('Phone'),

            DateColumn::name('created_at')
                ->label('Created at')
        ];
    }
}

After that we can show user table anywhere using this HTML code.

<!DOCTYPE html>
<html>
    <head>
        <title>Laravel 8 Livewire Datatables</title>
        @livewireStyles
        <link href="https://unpkg.com/[email protected]^2/dist/tailwind.min.css" rel="stylesheet">
    </head>
    <body>
        <div class="container mx-auto">
            <h1 class="py-2 text-xl text-center">Laravel 8 Livewire Datatables</h1>
            <div class="py-4">
                <livewire:users-table/>
            </div>
        </div>
    </body>
    @livewireScripts
</html>

I hope this will help you to implement datatables in Livewire. If you have any questions, please write in comments.