robinflyhigh / livewire-datatables
Requires
- php: ^7.2.5|^8.0
- illuminate/support: ^7.0|^8.0
- livewire/livewire: ^2.4.4
- maatwebsite/excel: ^3.1
Requires (Dev)
- laravel/legacy-factories: ^1.0.4
- orchestra/testbench: ^4.0|5.0|6.0
- phpunit/phpunit: ^8.0|9.0
- dev-master
- v0.6.8
- v0.6.7
- v0.6.6
- v0.6.5
- v0.6.4
- v0.6.3
- v0.6.2
- v0.6.1
- v0.6.0
- v0.5.4
- v0.5.3
- v0.5.2
- v0.5.1
- v0.5.0
- v0.4.3
- v0.4.2
- v0.4.1
- v0.4.0
- v0.3.1
- v0.3.0
- v0.2.2
- v0.2.1
- v0.2.0
- v0.1.3
- v0.1.2
- v0.1.1
- v0.1.0
- v0.0.4
- v0.0.3
- v0.0.2
- v0.0.1
- dev-analysis-L3Kbj6
- dev-analysis-64r1Lo
- dev-analysis-3wr0xr
- dev-thyseus-improve-link-to
- dev-complex-query-builder
- dev-analysis-3wZVoL
- dev-analysis-J2Lrmk
- dev-analysis-rdbGEZ
- dev-exports
- dev-analysis-jLbJRB
- dev-tw2
- dev-analysis-Rv7edK
- dev-pagination-search-fix
- dev-tailwind2
- dev-analysis-64Dxn4
- dev-truncate-search
- dev-query-builder
- dev-analysis-lKoEdw
- dev-lw2
- dev-selectable
- dev-bugfix
This package is auto-updated.
Last update: 2024-10-23 14:57:40 UTC
README
Features
- Use a model or query builder to supply data
- Mutate and format columns using preset or custom callbacks
- Sort data using column or computed column
- Filter using booleans, times, dates, selects or free text
- Create complex combined filters using the complex query builder
- Show / hide columns
Live Demo App
Demo App Repo
Requirements
Installation
You can install the package via composer:
composer require mediconesystems/livewire-datatables
Optional
You don't need to, but if you like you can publish the config file and blade template assets:
php artisan vendor:publish --provider="Mediconesystems\LivewireDatatables\LivewireDatatablesServiceProvider"
This will enable you to modify the blade views and apply your own styling, the datatables views will be published to resources/livewire/datatables. The config file contains the default time and date formats used throughout
- This can be useful if you're using Purge CSS on your project, to make sure all the livewire-datatables classes get included
Several of the built-in dynamic components use Alpine JS, so to remove flickers on page load, make sure you have
[x-cloak] { display: none; }
somewhere in your CSS
Basic Usage
- Use the
livewire-datatable
component in your blade view, and pass in a model:
... <livewire:datatable model="App\User" /> ...
Template Syntax
- There are many ways to modify the table by passing additional properties into the component:
<livewire:datatable model="App\User" include="id, name, dob, created_at" dates="dob" />
Props
Component Syntax
Create a livewire component that extends Mediconesystems\LivewireDatatables\LivewireDatatable
php artisan livewire:datatable foo
--> 'app/Http/Livewire/Foo.php'
php artisan livewire:datatable tables.bar
--> 'app/Http/Livewire/Tables/Bar.php'
Provide a datasource by declaring public property $model
OR public method builder()
that returns an instance of Illuminate\Database\Eloquent\Builder
php artisan livewire:datatable users-table --model=user
--> 'app/Http/Livewire/UsersTable.php' withpublic $model = User::class
Declare a public method columns
that returns an array containing one or more Mediconesystems\LivewireDatatables\Column
Columns
Columns can be built using any of the static methods below, and then their attributes assigned using fluent method chains.
There are additional specific types of Column; NumberColumn
, DateColumn
, TimeColumn
, using the correct one for your datatype will enable type-specific formatting and filtering:
class ComplexDemoTable extends LivewireDatatable { public function builder() { return User::query(); } public function columns() { return [ NumberColumn::name('id') ->label('ID') ->linkTo('job', 6), BooleanColumn::name('email_verified_at') ->label('Email Verified') ->format() ->filterable(), Column::name('name') ->defaultSort('asc') ->group('group1') ->searchable() ->hideable() ->filterable(), Column::name('planet.name') ->label('Planet') ->group('group1') ->searchable() ->hideable() ->filterable($this->planets), DateColumn::name('dob') ->label('DOB') ->group('group2') ->filterable() ->hide(), (new LabelColumn()) ->label('My custom heading') ->content('This fixed string appears in every row') ]; } }
Column Methods
Listener
The component will listen for the refreshLivewireDatatable
event, which allows you to refresh the table from external components.
Eloquent Column Names
Columns from Eloquent relations can be included using the normal eloquent dot notation, eg. planet.name
, Livewire Datatables will automatically add the necessary table joins to include the column. If the relationship is of a 'many' type (HasMany
, BelongsToMany
, HasManyThrough
) then Livewire Datatables will create an aggregated subquery (which is much more efficient than a join and group. Thanks @reinink). By default, the aggregate type will be count
for a numeric column and group_concat
for a string column, but this can be over-ridden using a colon delimeter;
NumberColumn::name('students.age:sum')->label('Student Sum'), NumberColumn::name('students.age:avg')->label('Student Avg'), NumberColumn::name('students.age:min')->label('Student Min'), NumberColumn::name('students.age:max')->label('Student Max'),
Column Groups
When you have a very big table with a lot of columns, it is possible to create 'column groups' that allows the user to toggle the visibility of a whole group at once. Use ->group('NAME')
at any column to achieve this.
You can human readable labels and translations of your groups via the groupLabels
property of your table:
class GroupDemoTable extends LivewireDatatable { public $groupLabels = [ 'group1' => 'app.translation_for_group_1' 'group2' => 'app.translation_for_group_2' ]; public function columns() { return [ Column::name('planets.name') ->group('group1') ->label('Planet'), Column::name('planets.name') ->group('group2') ->label('Planet'),
Custom column names
It is still possible to take full control over your table, you can define a builder
method using whatever query you like, using your own joins, groups whatever, and then name your columns using your normal SQL syntax:
public function builder() { return User::query() ->leftJoin('planets', 'planets.id', 'users.planet_id') ->leftJoin('moons', 'moons.id', 'planets.moon_id') ->groupBy('users.id'); } public function columns() { return [ NumberColumn::name('id') ->filterable(), Column::name('planets.name') ->label('Planet'), Column::raw('GROUP_CONCAT(planets.name SEPARATOR " | ") AS `Moon`'), ... }
Callbacks
Callbacks give you the freedom to perform any mutations you like on the data before displaying in the table.
- The callbacks are performed on the paginated results of the database query, so shouldn't use a ton of memory
- Callbacks will receive the chosen columns as their arguments.
- Callbacks can be defined inline as below, or as public methods on the Datatable class, referenced by passing the name as a string as the second argument to the callback method.
- If you want to format the result differently for export, use
->exportCallback(Closure $callback)
.
class CallbackDemoTable extends LivewireDatatable { public model = User::class public function columns() { return [ Column::name('users.id'), Column::name('users.dob')->format(), Column::callback(['dob', 'signup_date'], function ($dob, $signupDate) { $age = $signupDate->diffInYears($dob); return $age > 18 ? '<span class="text-red-500">' . $age . '</span>' : $age; })->exportCallback(function ($dob, $signupDate), { return $age = $signupDate->diffInYears($dob); }), ... } }
Views
You can specify that a column's output is piped directly into a separate blade view template.
- Template is specified using ususal laravel view helper syntax
- Views will receive the column's value as
$value
, and the whole query row as$row
class CallbackDemoTable extends LivewireDatatable { public model = User::class public function columns() { return [ Column::name('users.id'), Column::name('users.dob')->view('tables.dateview'), Column::name('users.signup_date')->format(), ]; }
'tables/dateview.blade.php' <span class="mx-4 my-2 bg-pink-500"> <x-date-thing :value="$value" /> </span>
Editable Columns
You can mark a column as editable using editable
This uses the view()
method above to pass the data into an Alpine/Livewire compnent that can directly update the underlying database data. Requires the column to have column
defined using standard Laravel naming. This is included as an example. Much more comprehensive custom editable columns with validation etc can be built using the callback or view methods above.
class EditableTable extends LivewireDatatable { public $model = User::class; public function columns() { return [ Column::name('id') ->label('ID') ->linkTo('job', 6), Column::name('email') ->editable(), ... ]; } }
Complex Query Builder
Just add $complex = true
to your Datatable Class and all filterable columns will be available in the complex query builder.
Features
- Combine rules and groups of rules using AND/OR logic
- Drag and drop rules around the interface
Persisting Queries (Requires AlpineJS v3 with $perist plugin)
- Add
$persistComplexQuery = true
to your class and queries will be stored in browser localstorage. - By default the localstorage key will be the class name. You can provide your own by setting the public property
$persistKey
or overridinggetPersistKeyProperty()
on the Datatable Class - eg: for user-specific persistence:
public function getPersistKeyProperty() { return Auth::id() . '-' . parent::getPersistKeyProperty(); }
Saving Queries
If you want to save permanently save queries you must provide 3 methods for adding, deleting and retrieving your saved queries using whatever logic you like:
public function saveQuery(String $name, Array $rules)
public function deleteQuery(Int $id)
public function getSavedQueries()
- In your save and delete methods, be sure to emit an
updateSavedQueries
livewire event and pass a fresh array of results (see example below)
Example:
This example shows saving queries using a conventional Laravel ComplexQuery model, that belongsTo a User
/* Migration */ class CreateComplexQueriesTable extends Migration { public function up() { Schema::create('complex_queries', function (Blueprint $table) { $table->id(); $table->unsignedInteger('user_id'); $table->string('table'); $table->json('rules'); $table->string('name'); $table->timestamps(); }); } } /* Model */ class ComplexQuery extends BaseModel { protected $casts = ['rules' => 'array']; public function user() { return $this->belongsTo(User::class); } } /* Datatable Class */ class TableWithSaving extends Livewire Datatable { ... public function saveQuery($name, $rules) { Auth::user()->complex_queries()->create([ 'table' => $this->name, 'name' => $name, 'rules' => $rules ]); $this->emit('updateSavedQueries', $this->getSavedQueries()); } public function deleteQuery($id) { ComplexQuery::destroy($id); $this->emit('updateSavedQueries', $this->getSavedQueries()); } public function getSavedQueries() { return Auth::user()->complex_queries()->where('table', $this->name)->get(); } ... }
Styling
I know it's not cool to provide a package with tons of opionated markup and styling. Most other packages seem to have gone down the route of passing optional classes around as arguments or config variables. My take is that because this is just blade with tailwind, you can publish the templates and do whatever you like to them - it should be obvious where the Livewire and Alpine moving parts are.
There are methods for applying styles to rows and cells. rowClasses
receives the $row
and the laravel loop variable as parameters. cellClasses
receives the $row
and $column
For example:
public function rowClasses($row, $loop) { return 'divide-x divide-gray-100 text-sm text-gray-900 ' . ($this->rowIsSelected($row) ? 'bg-yellow-100' : ($row->{'car.model'} === 'Ferrari' ? 'bg-red-500' : ($loop->even ? 'bg-gray-100' : 'bg-gray-50'))); } public function cellClasses($row, $column) { return 'text-sm ' . ($this->rowIsSelected($row) ? ' text-gray-900' : ($row->{'car.model'} === 'Ferrari' ? ' text-white' : ' text-gray-900')); }
You can change the default CSS classes applied by the rowClasses
and the cellClasses
methods by changing default_classes
in the livewire-datatables.php
config file.
You could also override the render method in your table's class to provide different templates for different tables.