Datatable
To create a livewire datatable component for, for example, "Tags" - run the following command:
php artisan make:livewire Tables/TagsTable
This creates the two files we need to edit:
CLASS: app/Http/Livewire/Tables/TagsTable.php
VIEW: resources/views/livewire/tables/tags-table.blade.php
The next step is to update the livewire component class by
- setting it to extend Table (rather than component) and
- then adding the required methods (query() and columns())
For example:
<?php
namespace App\Http\Livewire;
use Textstem\Models\Post;
use Textstem\Table\Column;
use Illuminate\Database\Eloquent\Builder;
class PostsTable extends Table
{
// this is needed to identify which model is being used when building
// a layout using the table component
public $resourceName = 'posts';
public function query(): Builder
{
return Post::query();
}
public function columns(): array
{
return [
Column::make('title', 'Title'),
Column::make('post_type', 'Type'),
Column::make('post_status', 'Status')->component('columns.formatters.status'),
Column::make('published', 'Published')->component('columns.formatters.yesno'),
Column::make('updated_at', 'Modified')->component('columns.formatters.timeago'),
];
}
}
You can delete the view blade file that was created unless you want to customise the table layout.
If you wish to cusomise the table layout, you can update the view blade file, looping through the columns to create the header, and then again for the table body like this:
<div>
<div class="relative overflow-x-auto ">
<table class="datatable">
<thead">
<tr>
@foreach($this->columns() as $column)
<x-columns.header
:column="$column"
:sortBy="$sortBy"
:sortDirection="$sortDirection" />
@endforeach
</tr>
</thead>
<tbody>
@foreach($this->data() as $row)
<tr class="bg-white border-b hover:bg-gray-50">
@foreach($this->columns() as $column)
<td>
<div class="">
<x-dynamic-component
:component="$column->component"
:value="$row[$column->key]"
>
</x-dynamic-component>
</div>
</td>
@endforeach
</tr>
@endforeach
</tbody>
</table>
</div>
<div class="my-4">
{{ $this->data()->links() }}
</div>
</div>