Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Advanced datatables using Laravel, Livewire, Tailwind CSS and Alpine JS

License

NotificationsYou must be signed in to change notification settings

MedicOneSystems/livewire-datatables

Repository files navigation

Latest Version on PackagistTotal Downloads

⚠️ Project Status: Unmaintained

Thank you to everyone who has used, contributed to, or supported this project. Unfortunately, I’m no longer able to actively maintain it.I wanted to be transparent so that you can make informed decisions about using or forking the code.

If you rely on this project and would like to take over maintenance or ownership, feel free to open an issue to discuss it. Otherwise, please treat this repository as archived and read-only.

Thanks again for your understanding and for being part of the project.

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 thecomplex query builder
  • Show / hide columns
  • Column groups
  • Mass Action (Bulk) Support

screenshot

Requirements

Installation

You can install the package via composer:

composer require mediconesystems/livewire-datatables

If you use laravel 9 first execute

composer require psr/simple-cache:^1.0 maatwebsite/excel

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 thelivewire-datatable component in your blade view, and pass in a model:
...<livewire:datatablemodel="App\User"name="all-users"/>...

Template Syntax

  • There are many ways to modify the table by passing additional properties into the component:
<livewire:datatablemodel="App\User"name="users"include="id, name, dob, created_at"dates="dob"/>

Attention: Please note that having multiple datatables on the same pageor more than one datatable of the sametype on different pages needs to have a uniquename attribute assigned to each one so they do not conflict with eachother as in the example above.

Props

PropertyArgumentsResultExample
modelString full model nameDefine the base model for the tablemodel="App\Post"
includeString| Array of column definitionsspecify columns to be shown in table, label can be specified by using | delimterinclude="name, email, dob|Birth Date, role"
excludeString| Array of column definitionscolumns are excluded from table:exclude="['created_at', 'updated_at']"
hideString| Array of column definitionscolumns are present, but start hiddenhidden="email_verified_at"
datesString| Array of column definitions [ and optional format in \delimited string]column values are formatted as per the default date format, or format can be included in string with | separator
timesString| Array of column definitions [optional format in \delimited string]column values are formatted as per the default time format, or format can be included in string with | separator
searchableString| Array of column namesDefines columns to be included in global searchsearchable="name, email"
sortString of column definition [and optional 'asc' or 'desc' (default: 'desc') in | delimited string]Specifies the column and direction for initial table sort. Default is column 0 descendingsort="name|asc"
hide-headerBoolean default:falseThe top row of the table including the column titles is removed if this istrue
hide-paginationBoolean default:falsePagination controls are removed if this istrue
per-pageInteger default: 10Number of rows per pageper-page="20"
exportableBoolean default:falseAllows table to be exported<livewire:datatable model="App/Post" exportable />
hideableStringgives ability to show/hide columns, accepts strings 'inline', 'buttons', or 'select'<livewire:datatable model="App/Post" hideable="inline" />
buttonsSlotStringblade view to be included immediately after the buttons at the top of the table in the component, which can therefore access public properties
beforeTableSlotStringblade view to be included immediately before the table in the component, which can therefore access public properties
afterTableSlotStringblade view to be included immediately after the table in the component, which can therefore access public propertiesdemo

Component Syntax

Create a livewire component that extendsMediconesystems\LivewireDatatables\LivewireDatatable

php artisan make:livewire-datatable foo --> 'app/Http/Livewire/Foo.php'

php artisan make:livewire-datatable tables.bar --> 'app/Http/Livewire/Tables/Bar.php'

Provide a datasource by declaring public property$modelOR public methodbuilder() that returns an instance ofIlluminate\Database\Eloquent\Builder

php artisan make:livewire-datatable users-table --model=user --> 'app/Http/Livewire/UsersTable.php' withpublic $model = User::class

Declare a public methodcolumns that returns an array containing one or moreMediconesystems\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:

ClassDescription
ColumnGeneric string-based column. Filter will be a text input
NumberColumnNumber-based column. Filters will be a numeric range
BooleanColumnValues will be automatically formatted to a yes/no icon, filters will be yes/no
DateColumnValues will be automatically formatted to the default date format. Filters will be a date range
TimeColumnValues will be automatically formatted to the default time format. Filters will be a time range
LabelColumnFixed header string ("label") with fixed content string in every row. No SQL is executed at all

class ComplexDemoTableextends LivewireDatatable{publicfunctionbuilder()    {return User::query();    }publicfunctioncolumns()    {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),// Column that counts every line from 1 upwards, independent of content            Column::index($this);            DateColumn::name('dob')                ->label('DOB')                ->group('group2')                ->filterable()                ->hide(),            (newLabelColumn())                ->label('My custom heading')                ->content('This fixed string appears in every row'),            NumberColumn::name('dollars_spent')                ->enableSummary(),        ];    }}

Column Methods

MethodArgumentsResultExample
staticnameString $columnBuilds a column from column definition, which can be eith Eloquent or SQL dot notation (see below)Column::name('name')
staticrawString $rawSqlStatementBuilds a column from raw SQL statement. Must include "... ASalias"Column::raw("CONCAT(ROUND(DATEDIFF(NOW(), users.dob) / planets.orbital_period, 1) AS `Native Age`")
staticcallbackArray|String $columns,Closure|String $callbackPasses the columns from the first argument into the callback to allow custom mutations. The callback can be a method on the table class, or inline(see below)
staticscopeString $scope,String $aliasBuilds a column from a scope on the parent modelColumn::scope('selectLastLogin', 'Last Login')
staticdelete[String $primaryKey default: 'id']Adds a column with a delete button, which will call$this->model::destroy($primaryKey)Column::delete()
staticcheckbox[String $column default: 'id']Adds a column with a checkbox. The component public property$selected will contain an array of the named column from checked rows,Column::checkbox()
labelString $nameChanges the display name of a columnColumn::name('id')->label('ID)
groupString $groupAssign the column to a group. Allows to toggle the visibility of all columns of a group at onceColumn::name('id')->group('my-group')
format[String $format]Formats the column value according to type. Dates/times will use the default format or the argumentColumn::name('email_verified_at')->filterable(),
hideMarks column to start as hiddenColumn::name('id')->hidden()
sortByString|Expression $columnChanges the query by which the column is sortedColumn::name('dob')->sortBy('DATE_FORMAT(users.dob, "%m%d%Y")'),
truncate[Integer $length (default: 16)]Truncates column to $length and provides full-text in a tooltip. Usesview('livewire-datatables::tooltip)Column::name('biography)->truncate(30)
linkToString $model, [Integer $pad]Replaces the value with a link to"/$model/$value". Useful for ID columns. Optional zero-padding. Usesview('livewire-datatables::link)Column::name('id')->linkTo('user')
linkString $href, [String $slot]Let the content of the column render as a link. You may use {{ }} syntax to fill the url with any attributes of the current row. Usesview('livewire-datatables::link)Column::name('first_name')->link('/users/{{slug}}/edit', 'edit {{first_name}} {{last_name}}')
round[Integer $precision (default: 0)]Rounds value to given precisionColumn::name('age')->round()
defaultSort[String $direction (default: 'desc')]Marks the column as the default search columnColumn::name('name')->defaultSort('asc')
searchableIncludes the column in the global searchColumn::name('name')->searchable()
hideableThe user is able to toggle the visibility of this columnColumn::name('name')->hideable()
filterable[Array $options], [String $filterScope]Adds a filter to the column, according to Column type. If an array of options is passed it wil be used to populate a select input. If the column is a scope column then the name of the filter scope must also be passedColumn::name('allegiance')->filterable(['Rebellion', 'Empire'])
unwrapPrevents the content of the column from being wrapped in multiple linesColumn::name('oneliner')->unwrap()
filterOnString/Array $statementAllows you to specify a column name or sql statement upon which to perform the filter (must use SQL syntax, not Eloquent eg.'users.name' instead of'user.name'). Useful if using a callback to modify the displayed values. Can pass a single string or array of strings which will be combined withORColumn::callback(['name', 'allegiance'], function ($name, $allegiance) { return "$name is allied to $allegiance"; })->filterable(['Rebellion', 'Empire'])->filterOn('users.allegiance')
viewString $viewNamePasses the column value, whole row of values, and any additional parameters to a view template(see below)
editableMarks the column as editable(see below)
alignCenterCenter-aligns column headerand contentsColumn::delete()->alignCenter()
alignRightRight-aligns column headerand contentsColumn::delete()->alignRight()
contentAlignCenterCenter-aligns column contentsColumn::delete()->contentAlignCenter()
contentAlignRightRight-aligns column contentsColumn::delete()->contentAlignRight()
headerAlignCenterCenter-aligns column headerColumn::delete()->headerAlignCenter()
headerAlignRightRight-aligns column headerColumn::delete()->headerAlignRight()
editableMarks the column as editable(see below)
exportCallbackClosure $callbackReformats the result when exporting(see below)
excludeFromExportExcludes the column from exportColumn::name('email')->excludeFromExport()
unsortablePrevents the column being sortableColumn::name('email')->unsortable()

Listener

The component will listen for therefreshLivewireDatatable 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 becount for a numeric column andgroup_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 thegroupLabels property of your table:

class GroupDemoTableextends LivewireDatatable{public$groupLabels = ['group1' =>'app.translation_for_group_1','group2' =>'app.translation_for_group_2'    ];publicfunction columns()    {return [            Column::name('planets.name')                ->group('group1')                ->label('Planet'),            Column::name('planets.name')                ->group('group2')                ->label('Planet'),

Summary row

If you need to summarize all cells of a specific column, you can useenableSummary():

publicfunction columns(){return [        Column::name('dollars_spent')            ->label('Expenses in Dollar')            ->enableSummary(),        Column::name('euro_spent')            ->label('Expenses in Euro')            ->enableSummary(),

Mass (Bulk) Action

If you want to be able to act upon several records at once, you can use thebuildActions() method in your Table:

publicfunctionbuildActions()    {return [            Action::value('edit')->label('Edit Selected')->group('Default Options')->callback(function ($mode,$items) {// $items contains an array with the primary keys of the selected items            }),            Action::value('update')->label('Update Selected')->group('Default Options')->callback(function ($mode,$items) {// $items contains an array with the primary keys of the selected items            }),            Action::groupBy('Export Options',function () {return [                    Action::value('csv')->label('Export CSV')->export('SalesOrders.csv'),                    Action::value('html')->label('Export HTML')->export('SalesOrders.html'),                    Action::value('xlsx')->label('Export XLSX')->export('SalesOrders.xlsx')->styles($this->exportStyles)->widths($this->exportWidths)                ];            }),        ];    }

Mass Action Style

If you only have small style adjustments to the Bulk Action Dropdown you can adjust some settings here:

publicfunctiongetExportStylesProperty()    {return ['1'  => ['font' => ['bold' =>true]],'B2' => ['font' => ['italic' =>true]],'C'  => ['font' => ['size' =>16]],        ];    }publicfunctiongetExportWidthsProperty()    {return ['A' =>55,'B' =>45,        ];    }

Pin Records

If you want to give your users the ability to pin specific records to be able to, for example, comparethem with each other, you can use the CanPinRecords trait. Ensure to have at least one Checkbox Columnso the user can select records:

useMediconesystems\LivewireDatatables\Traits\CanPinRecords;class RecordTableextends LivewireDatatable{use CanPinRecords;public$model = Record::class;publicfunction columns()    {return [            Column::checkbox(),// ...

Custom column names

It is still possible to take full control over your table, you can define abuilder method using whatever query you like, using your own joins, groups whatever, and then name your columns using your normal SQL syntax:

publicfunctionbuilder(){return User::query()        ->leftJoin('planets','planets.id','users.planet_id')        ->leftJoin('moons','moons.id','planets.moon_id')        ->groupBy('users.id');}publicfunctioncolumns(){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 CallbackDemoTableextends LivewireDatatable{public$model = User::class    publicfunctioncolumns()    {        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>' .$age .'</span>'                    :$age;            })->exportCallback(function ($dob,$signupDate), {return$age =$signupDate->diffInYears($dob);            }),            ...    }}

Default Filters

If you want to have a default filter applied to your table, you can use thedefaultFilters property. ThedefaultFilter should be an Array of column names and the default filter value to use for. When a persisted filter ($this->persistFilters is true and session values are available) is available, it will override the default filters.

In the example below, the table will by default be filtered by rows where thedeleted_at column is false. If the user has a persisted filter for thedeleted_at column, the default filter will be ignored.

class CallbackDemoTableextends LivewireDatatable{public$defaultFilters = ['deleted_at' =>'0',    ];publicfunctionbuilder()    {return User::query()->withTrashed();    }publicfunctioncolumns()    {return [            Column::name('id'),            BooleanColumn::name('deleted_at')->filterable(),        ];    }}

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 CallbackDemoTableextends LivewireDatatable{public$model = User::class    publicfunctioncolumns()    {        return [            Column::name('users.id'),            Column::name('users.dob')->view('tables.dateview'),            Column::name('users.signup_date')->format(),        ];    }
'tables/dateview.blade.php'<spanclass="mx-4 my-2 bg-pink-500"><x-date-thing:value="$value"/></span>

Editable Columns

You can mark a column as editable usingeditableThis uses theview() method above to pass the data into an Alpine/Livewire compnent that can directly update the underlying database data. Requires the column to havecolumn 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 EditableTableextends LivewireDatatable{public$model = User::class;publicfunction 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

image

Persisting Queries (Requires AlpineJS v3 with $persist 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:
publicfunctiongetPersistKeyProperty(){return Auth::id() .'-' .parent::getPersistKeyProperty();}

Saving Queries

If you want to 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 anupdateSavedQueries 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 CreateComplexQueriesTableextends Migration{publicfunctionup()    {        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 ComplexQueryextends BaseModel{protected$casts = ['rules' =>'array'];publicfunctionuser()    {return$this->belongsTo(User::class);    }}/* Datatable Class */class TableWithSavingextends LivewireDatatable{    ...publicfunctionsaveQuery($name,$rules)    {        Auth::user()->complex_queries()->create(['table' =>$this->name,'name' =>$name,'rules' =>$rules        ]);$this->emit('updateSavedQueries',$this->getSavedQueries());    }publicfunctiondeleteQuery($id)    {        ComplexQuery::destroy($id);$this->emit('updateSavedQueries',$this->getSavedQueries());    }publicfunctiongetSavedQueries()    {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 thelaravel loop variable as parameters.cellClasses receives the$row and$column

For example:

publicfunctionrowClasses($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')));}publicfunctioncellClasses($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 therowClasses and thecellClasses methods by changingdefault_classes in thelivewire-datatables.php config file.

You could also override the render method in your table's class to provide different templates for different tables.

Credits and Influences

About

Advanced datatables using Laravel, Livewire, Tailwind CSS and Alpine JS

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Contributors70


[8]ページ先頭

©2009-2025 Movatter.jp