18 |
--------------------------------------------------------------------------------
/LICENSE.md:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) Mark Salmon
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
--------------------------------------------------------------------------------
/resources/views/livewire/datatables/editable.blade.php:
--------------------------------------------------------------------------------
1 |
40 |
41 |
55 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are **welcome** and will be fully **credited**.
4 |
5 | Please read and understand the contribution guide before creating an issue or pull request.
6 |
7 | ## Etiquette
8 |
9 | This project is open source, and as such, the maintainers give their free time to build and maintain the source code
10 | held within. They make the code freely available in the hope that it will be of use to other developers. It would be
11 | extremely unfair for them to suffer abuse or anger for their hard work.
12 |
13 | Please be considerate towards maintainers when raising issues or presenting pull requests. Let's show the
14 | world that developers are civilized and selfless people.
15 |
16 | It's the duty of the maintainer to ensure that all submissions to the project are of sufficient
17 | quality to benefit the project. Many developers have different skillsets, strengths, and weaknesses. Respect the maintainer's decision, and do not be upset or abusive if your submission is not used.
18 |
19 | ## Viability
20 |
21 | When requesting or submitting new features, first consider whether it might be useful to others. Open
22 | source projects are used by many developers, who may have entirely different needs to your own. Think about
23 | whether or not your feature is likely to be used by other users of the project.
24 |
25 | ## Procedure
26 |
27 | Before filing an issue:
28 |
29 | - Attempt to replicate the problem, to ensure that it wasn't a coincidental incident.
30 | - Check to make sure your feature suggestion isn't already present within the project.
31 | - Check the pull requests tab to ensure that the bug doesn't have a fix in progress.
32 | - Check the pull requests tab to ensure that the feature isn't already in progress.
33 |
34 | Before submitting a pull request:
35 |
36 | - Check the codebase to ensure that your feature doesn't already exist.
37 | - Check the pull requests to ensure that another person hasn't already submitted the feature or fix.
38 |
39 | ## Requirements
40 |
41 | If the project maintainer has any additional requirements, you will find them listed here.
42 |
43 | - **[PSR-2 Coding Standard](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md)** - The easiest way to apply the conventions is to install [PHP Code Sniffer](https://pear.php.net/package/PHP_CodeSniffer).
44 |
45 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests.
46 |
47 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
48 |
49 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](https://semver.org/). Randomly breaking public APIs is not an option.
50 |
51 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
52 |
53 | - **Send coherent history** - Make sure each individual commit in your pull request is meaningful. If you had to make multiple intermediate commits while developing, please [squash them](https://www.git-scm.com/book/en/v2/Git-Tools-Rewriting-History#Changing-Multiple-Commit-Messages) before submitting.
54 |
55 | **Happy coding**!
56 |
--------------------------------------------------------------------------------
/src/Commands/ComponentParser.php:
--------------------------------------------------------------------------------
1 | model = $model;
19 |
20 | $this->baseClassNamespace = $classNamespace;
21 |
22 | $classPath = static::generatePathFromNamespace($classNamespace);
23 |
24 | $this->baseClassPath = rtrim($classPath, DIRECTORY_SEPARATOR) . '/';
25 |
26 | $directories = preg_split('/[.\/]+/', $rawCommand);
27 |
28 | $camelCase = Str::camel(array_pop($directories));
29 | $kebabCase = Str::kebab($camelCase);
30 |
31 | $this->component = $kebabCase;
32 | $this->componentClass = Str::studly($this->component);
33 |
34 | $this->directories = array_map([Str::class, 'studly'], $directories);
35 | }
36 |
37 | public function component()
38 | {
39 | return $this->component;
40 | }
41 |
42 | public function classPath()
43 | {
44 | return $this->baseClassPath . collect()
45 | ->concat($this->directories)
46 | ->push($this->classFile())
47 | ->implode('/');
48 | }
49 |
50 | public function relativeClassPath()
51 | {
52 | return Str::replaceFirst(base_path() . DIRECTORY_SEPARATOR, '', $this->classPath());
53 | }
54 |
55 | public function classFile()
56 | {
57 | return $this->componentClass . '.php';
58 | }
59 |
60 | public function classNamespace()
61 | {
62 | return empty($this->directories)
63 | ? $this->baseClassNamespace
64 | : $this->baseClassNamespace . '\\' . collect()
65 | ->concat($this->directories)
66 | ->map([Str::class, 'studly'])
67 | ->implode('\\');
68 | }
69 |
70 | public function className()
71 | {
72 | return $this->componentClass;
73 | }
74 |
75 | public function classContents()
76 | {
77 | if ($this->model) {
78 | $template = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'datatable-model.stub');
79 |
80 | return preg_replace_array(
81 | ['/\[namespace\]/', '/\[use\]/', '/\[class\]/', '/\[model\]/'],
82 | [
83 | $this->classNamespace(),
84 | config('livewire-datatables.model_namespace', 'App') . '\\' . Str::studly($this->model),
85 | $this->className(),
86 | Str::studly($this->model),
87 | ],
88 | $template
89 | );
90 | } else {
91 | $template = file_get_contents(__DIR__ . DIRECTORY_SEPARATOR . 'datatable.stub');
92 |
93 | return preg_replace_array(
94 | ['/\[namespace\]/', '/\[class\]/'],
95 | [$this->classNamespace(), $this->className()],
96 | $template
97 | );
98 | }
99 | }
100 |
101 | public static function generatePathFromNamespace($namespace)
102 | {
103 | $name = Str::replaceFirst(app()->getNamespace(), '', $namespace);
104 |
105 | return app('path') . '/' . str_replace('\\', '/', $name);
106 | }
107 | }
108 |
--------------------------------------------------------------------------------
/resources/views/livewire/datatables/delete.blade.php:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
8 |
12 |
13 |
14 |
15 |
22 |
23 |
30 |
31 |
32 |
33 |
34 | {{ __('Delete') }} {{ $value }}
35 |
36 |
37 |
38 | {{ __('Are you sure?')}}
39 |
40 |
41 |
42 |
45 |
46 |
47 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/config/livewire-datatables.php:
--------------------------------------------------------------------------------
1 | 'H:i',
15 | 'default_date_format' => 'd/m/Y',
16 | 'default_datetime_format' => 'd/m/Y H:i',
17 |
18 | /*
19 | |--------------------------------------------------------------------------
20 | | Default Carbon Formats
21 | |--------------------------------------------------------------------------
22 | | The default formats that are used for TimeColumn & DateColumn.
23 | | You can use the formatting characters from the PHP DateTime class.
24 | | More info: https://www.php.net/manual/en/datetime.format.php
25 | |
26 | */
27 |
28 | 'default_time_start' => '0000-00-00',
29 | 'default_time_end' => '9999-12-31',
30 |
31 | // Defaults that work with smalldatetime in SQL Server
32 | // 'default_time_start' => '1900-01-01',
33 | // 'default_time_end' => '2079-06-06',
34 |
35 | /*
36 | |--------------------------------------------------------------------------
37 | | Surpress Search Highlights
38 | |--------------------------------------------------------------------------
39 | | When enabled, matching text won't be highlighted in the search results
40 | | while searching.
41 | |
42 | */
43 |
44 | 'suppress_search_highlights' => false,
45 |
46 | /*
47 | |--------------------------------------------------------------------------
48 | | Per Page Options
49 | |--------------------------------------------------------------------------
50 | | Sets the options to choose from in the `Per Page`dropdown.
51 | |
52 | */
53 |
54 | 'per_page_options' => [10, 25, 50, 100],
55 |
56 | /*
57 | |--------------------------------------------------------------------------
58 | | Default Per Page
59 | |--------------------------------------------------------------------------
60 | | Sets the default amount of rows to display per page.
61 | |
62 | */
63 |
64 | 'default_per_page' => 10,
65 |
66 | /*
67 | |--------------------------------------------------------------------------
68 | | Model Namespace
69 | |--------------------------------------------------------------------------
70 | | Sets the default namespace to be used when generating a new Datatables
71 | | component.
72 | |
73 | */
74 |
75 | 'model_namespace' => 'App',
76 |
77 | /*
78 | |--------------------------------------------------------------------------
79 | | Default Sortable
80 | |--------------------------------------------------------------------------
81 | | Should a column of a datatable be sortable by default ?
82 | |
83 | */
84 |
85 | 'default_sortable' => true,
86 |
87 | /*
88 | |--------------------------------------------------------------------------
89 | | Default CSS classes
90 | |--------------------------------------------------------------------------
91 | |
92 | | Sets the default classes that will be applied to each row and class
93 | | if the rowClasses() and cellClasses() functions are not overrided.
94 | |
95 | */
96 |
97 | 'default_classes' => [
98 | 'row' => [
99 | 'even' => 'divide-x divide-gray-100 text-sm text-gray-900 bg-gray-100',
100 | 'odd' => 'divide-x divide-gray-100 text-sm text-gray-900 bg-gray-50',
101 | 'selected' => 'divide-x divide-gray-100 text-sm text-gray-900 bg-yellow-100',
102 | ],
103 | 'cell' => 'whitespace-no-wrap text-sm text-gray-900 px-6 py-2',
104 | ],
105 | ];
106 |
--------------------------------------------------------------------------------
/resources/views/livewire/datatables/complex-query-group.blade.php:
--------------------------------------------------------------------------------
1 |
240 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Livewire Datatables
2 |
3 | [](https://packagist.org/packages/mediconesystems/livewire-datatables)
4 | [](https://packagist.org/packages/mediconesystems/livewire-datatables)
5 |
6 | ⚠️ Project Status: Unmaintained
7 |
8 | Thank you to everyone who has used, contributed to, or supported this project. Unfortunately, I’m no longer able to actively maintain it.
9 | I wanted to be transparent so that you can make informed decisions about using or forking the code.
10 |
11 | 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.
12 |
13 | Thanks again for your understanding and for being part of the project.
14 |
15 | ### Features
16 | - Use a model or query builder to supply data
17 | - Mutate and format columns using preset or custom callbacks
18 | - Sort data using column or computed column
19 | - Filter using booleans, times, dates, selects or free text
20 | - Create complex combined filters using the [complex query builder](#complex-query-builder)
21 | - Show / hide columns
22 | - Column groups
23 | - Mass Action (Bulk) Support
24 |
25 | ## [Demo App Repo](https://github.com/MedicOneSystems/demo-livewire-datatables)
26 |
27 | 
28 |
29 | ## Requirements
30 | - [Laravel 7, 8 or 9](https://laravel.com/docs/9.x)
31 | - [Livewire](https://laravel-livewire.com/)
32 | - [Tailwind](https://tailwindcss.com/)
33 | - [Alpine JS](https://github.com/alpinejs/alpine)
34 |
35 | ## Installation
36 |
37 | You can install the package via composer:
38 |
39 | ```bash
40 | composer require mediconesystems/livewire-datatables
41 | ```
42 | If you use laravel 9 first execute
43 | ```bash
44 | composer require psr/simple-cache:^1.0 maatwebsite/excel
45 | ```
46 |
47 | ### Optional
48 | You don't need to, but if you like you can publish the config file and blade template assets:
49 | ```bash
50 | php artisan vendor:publish --provider="Mediconesystems\LivewireDatatables\LivewireDatatablesServiceProvider"
51 | ```
52 | 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
53 | > - This can be useful if you're using Purge CSS on your project, to make sure all the livewire-datatables classes get included
54 |
55 | Several of the built-in dynamic components use Alpine JS, so to remove flickers on page load, make sure you have
56 | ```css
57 | [x-cloak] {
58 | display: none;
59 | }
60 | ```
61 | somewhere in your CSS
62 |
63 | ## Basic Usage
64 |
65 | - Use the ```livewire-datatable``` component in your blade view, and pass in a model:
66 | ```html
67 | ...
68 |
69 |
70 |
71 | ...
72 | ```
73 |
74 | ## Template Syntax
75 | - There are many ways to modify the table by passing additional properties into the component:
76 | ```html
77 |
83 | ```
84 |
85 | *Attention*: Please note that having multiple datatables on the same page _or_ more than one datatable of the same
86 | type on different pages needs to have a unique `name` attribute assigned to each one so they do not conflict with each
87 | other as in the example above.
88 |
89 | ### Props
90 | | Property | Arguments | Result | Example |
91 | |----|----|------------------------------------------------------------------------------------------------------------------------------------------------|----|
92 | |**model**|*String* full model name| Define the base model for the table | ```model="App\Post"```|
93 | |**include**|*String\| Array* of column definitions |specify columns to be shown in table, label can be specified by using \| delimter | ```include="name, email, dob\|Birth Date, role"```|
94 | |**exclude**|*String\| Array* of column definitions |columns are excluded from table| ```:exclude="['created_at', 'updated_at']"```|
95 | |**hide**|*String\| Array* of column definitions |columns are present, but start hidden|```hidden="email_verified_at"```|
96 | |**dates**|*String\| 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 | ```:dates="['dob\|lS F y', 'created_at']"```|
97 | |**times**|*String\| 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 | ```'bedtime\|g:i A'```|
98 | |**searchable**|*String\| Array* of column names | Defines columns to be included in global search | ```searchable="name, email"```|
99 | |**sort**|*String* 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 descending | ```sort="name\|asc"```|
100 | |**hide-header**|*Boolean* default: *false*| The top row of the table including the column titles is removed if this is ```true``` | |
101 | |**hide-pagination**|*Boolean* default: *false*| Pagination controls are removed if this is ```true``` | |
102 | |**per-page**|*Integer* default: 10| Number of rows per page | ```per-page="20"``` |
103 | |**exportable**|*Boolean* default: *false*| Allows table to be exported | `````` |
104 | |**hideable**| _String_ | gives ability to show/hide columns, accepts strings 'inline', 'buttons', or 'select' | `````` |
105 | |**buttonsSlot**| _String_ | blade view to be included immediately after the buttons at the top of the table in the component, which can therefore access public properties | |
106 | |**beforeTableSlot**| _String_ | blade view to be included immediately before the table in the component, which can therefore access public properties | |
107 | |**afterTableSlot**| _String_ | blade view to be included immediately after the table in the component, which can therefore access public properties | [demo](https://livewire-datatables.com/complex) |
108 | ---
109 |
110 |
111 | ## Component Syntax
112 |
113 | ### Create a livewire component that extends ```Mediconesystems\LivewireDatatables\LivewireDatatable```
114 | > ```php artisan make:livewire-datatable foo``` --> 'app/Http/Livewire/Foo.php'
115 |
116 | > ```php artisan make:livewire-datatable tables.bar``` --> 'app/Http/Livewire/Tables/Bar.php'
117 |
118 | ### Provide a datasource by declaring public property ```$model``` **OR** public method ```builder()``` that returns an instance of ```Illuminate\Database\Eloquent\Builder```
119 | > ```php artisan make:livewire-datatable users-table --model=user``` --> 'app/Http/Livewire/UsersTable.php' with ```public $model = User::class```
120 |
121 | ### Declare a public method ```columns``` that returns an array containing one or more ```Mediconesystems\LivewireDatatables\Column```
122 |
123 | ## Columns
124 | Columns can be built using any of the static methods below, and then their attributes assigned using fluent method chains.
125 | There are additional specific types of Column; ```NumberColumn```, ```DateColumn```, ```TimeColumn```, using the correct one for your datatype will enable type-specific formatting and filtering:
126 |
127 | | Class | Description |
128 | |---|---|
129 | |Column|Generic string-based column. Filter will be a text input|
130 | |NumberColumn| Number-based column. Filters will be a numeric range|
131 | |BooleanColumn| Values will be automatically formatted to a yes/no icon, filters will be yes/no|
132 | |DateColumn| Values will be automatically formatted to the default date format. Filters will be a date range|
133 | |TimeColumn| Values will be automatically formatted to the default time format. Filters will be a time range|
134 | |LabelColumn| Fixed header string ("label") with fixed content string in every row. No SQL is executed at all|
135 | ___
136 |
137 | ```php
138 | class ComplexDemoTable extends LivewireDatatable
139 | {
140 | public function builder()
141 | {
142 | return User::query();
143 | }
144 |
145 | public function columns()
146 | {
147 | return [
148 | NumberColumn::name('id')
149 | ->label('ID')
150 | ->linkTo('job', 6),
151 |
152 | BooleanColumn::name('email_verified_at')
153 | ->label('Email Verified')
154 | ->format()
155 | ->filterable(),
156 |
157 | Column::name('name')
158 | ->defaultSort('asc')
159 | ->group('group1')
160 | ->searchable()
161 | ->hideable()
162 | ->filterable(),
163 |
164 | Column::name('planet.name')
165 | ->label('Planet')
166 | ->group('group1')
167 | ->searchable()
168 | ->hideable()
169 | ->filterable($this->planets),
170 |
171 | // Column that counts every line from 1 upwards, independent of content
172 | Column::index($this);
173 |
174 | DateColumn::name('dob')
175 | ->label('DOB')
176 | ->group('group2')
177 | ->filterable()
178 | ->hide(),
179 |
180 | (new LabelColumn())
181 | ->label('My custom heading')
182 | ->content('This fixed string appears in every row'),
183 |
184 | NumberColumn::name('dollars_spent')
185 | ->enableSummary(),
186 | ];
187 | }
188 | }
189 | ```
190 |
191 | ### Column Methods
192 | | Method | Arguments | Result | Example |
193 | |----|----|----|----|
194 | |_static_ **name**| *String* $column |Builds a column from column definition, which can be eith Eloquent or SQL dot notation (see below) |```Column::name('name')```|
195 | |_static_ **raw**| *String* $rawSqlStatement|Builds a column from raw SQL statement. Must include "... AS _alias_"|```Column::raw("CONCAT(ROUND(DATEDIFF(NOW(), users.dob) / planets.orbital_period, 1) AS `Native Age`")```|
196 | |_static_ **callback**|*Array\|String* $columns, *Closure\|String* $callback| Passes 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)_|
197 | |_static_ **scope**|*String* $scope, *String* $alias|Builds a column from a scope on the parent model|```Column::scope('selectLastLogin', 'Last Login')```|
198 | |_static_ **delete**|[*String* $primaryKey default: 'id']|Adds a column with a delete button, which will call ```$this->model::destroy($primaryKey)```|```Column::delete()```|
199 | |_static_ **checkbox**|[*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()```|
200 | |**label**|*String* $name|Changes the display name of a column|```Column::name('id')->label('ID)```|
201 | |**group**|*String* $group|Assign the column to a group. Allows to toggle the visibility of all columns of a group at once|```Column::name('id')->group('my-group')```|
202 | |**format**|[*String* $format]|Formats the column value according to type. Dates/times will use the default format or the argument |```Column::name('email_verified_at')->filterable(),```|
203 | |**hide**| |Marks column to start as hidden|```Column::name('id')->hidden()```|
204 | |**sortBy**|*String\|Expression* $column|Changes the query by which the column is sorted|```Column::name('dob')->sortBy('DATE_FORMAT(users.dob, "%m%d%Y")'),```|
205 | |**truncate**|[*Integer* $length (default: 16)]Truncates column to $length and provides full-text in a tooltip. Uses ```view('livewire-datatables::tooltip)```|```Column::name('biography)->truncate(30)```|
206 | |**linkTo**|*String* $model, [*Integer* $pad]|Replaces the value with a link to ```"/$model/$value"```. Useful for ID columns. Optional zero-padding. Uses ```view('livewire-datatables::link)```|```Column::name('id')->linkTo('user')```|
207 | |**link**|*String* $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. Uses ```view('livewire-datatables::link)```|```Column::name('first_name')->link('/users/{{slug}}/edit', 'edit {{first_name}} {{last_name}}')```|
208 | |**round**|[*Integer* $precision (default: 0)]|Rounds value to given precision|```Column::name('age')->round()```|
209 | |**defaultSort**|[*String* $direction (default: 'desc')]|Marks the column as the default search column|```Column::name('name')->defaultSort('asc')```|
210 | |**searchable**| |Includes the column in the global search|```Column::name('name')->searchable()```|
211 | |**hideable**| |The user is able to toggle the visibility of this column|```Column::name('name')->hideable()```|
212 | |**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 passed|```Column::name('allegiance')->filterable(['Rebellion', 'Empire'])```|
213 | |**unwrap**| | Prevents the content of the column from being wrapped in multiple lines |```Column::name('oneliner')->unwrap()```|
214 | |**filterOn**|*String/Array* $statement|Allows 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 with ```OR```|```Column::callback(['name', 'allegiance'], function ($name, $allegiance) { return "$name is allied to $allegiance"; })->filterable(['Rebellion', 'Empire'])->filterOn('users.allegiance')```|
215 | |**view**|*String* $viewName| Passes the column value, whole row of values, and any additional parameters to a view template | _(see below)_|
216 | |**editable**| | Marks the column as editable | _(see below)_|
217 | |**alignCenter**| | Center-aligns column header _and_ contents |```Column::delete()->alignCenter()```|
218 | |**alignRight**| | Right-aligns column header _and_ contents |```Column::delete()->alignRight()```|
219 | |**contentAlignCenter**| | Center-aligns column contents |```Column::delete()->contentAlignCenter()```|
220 | |**contentAlignRight**| | Right-aligns column contents |```Column::delete()->contentAlignRight()```|
221 | |**headerAlignCenter**| | Center-aligns column header |```Column::delete()->headerAlignCenter()```|
222 | |**headerAlignRight**| | Right-aligns column header |```Column::delete()->headerAlignRight()```|
223 | |**editable**| | Marks the column as editable | _(see below)_|
224 | |**exportCallback**| Closure $callback | Reformats the result when exporting | _(see below)_ |
225 | |**excludeFromExport**| | Excludes the column from export |```Column::name('email')->excludeFromExport()```|
226 | |**unsortable**| | Prevents the column being sortable |```Column::name('email')->unsortable()```|
227 | ___
228 |
229 | ### Listener
230 | The component will listen for the ```refreshLivewireDatatable``` event, which allows you to refresh the table from external components.
231 |
232 | ### Eloquent Column Names
233 | 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](https://eloquent-course.reinink.ca/)). 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;
234 |
235 | ```php
236 | NumberColumn::name('students.age:sum')->label('Student Sum'),
237 |
238 | NumberColumn::name('students.age:avg')->label('Student Avg'),
239 |
240 | NumberColumn::name('students.age:min')->label('Student Min'),
241 |
242 | NumberColumn::name('students.age:max')->label('Student Max'),
243 | ```
244 |
245 | ### Column Groups
246 |
247 | 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.
248 | You can human readable labels and translations of your groups via the `groupLabels` property of your table:
249 |
250 | ```php
251 | class GroupDemoTable extends LivewireDatatable
252 | {
253 | public $groupLabels = [
254 | 'group1' => 'app.translation_for_group_1',
255 | 'group2' => 'app.translation_for_group_2'
256 | ];
257 |
258 | public function columns()
259 | {
260 | return [
261 | Column::name('planets.name')
262 | ->group('group1')
263 | ->label('Planet'),
264 |
265 | Column::name('planets.name')
266 | ->group('group2')
267 | ->label('Planet'),
268 | ```
269 |
270 | ### Summary row
271 | If you need to summarize all cells of a specific column, you can use `enableSummary()`:
272 |
273 | ```php
274 | public function columns()
275 | {
276 | return [
277 | Column::name('dollars_spent')
278 | ->label('Expenses in Dollar')
279 | ->enableSummary(),
280 |
281 | Column::name('euro_spent')
282 | ->label('Expenses in Euro')
283 | ->enableSummary(),
284 | ```
285 |
286 | ### Mass (Bulk) Action
287 |
288 | If you want to be able to act upon several records at once, you can use the `buildActions()` method in your Table:
289 |
290 | ```php
291 | public function buildActions()
292 | {
293 | return [
294 |
295 | Action::value('edit')->label('Edit Selected')->group('Default Options')->callback(function ($mode, $items) {
296 | // $items contains an array with the primary keys of the selected items
297 | }),
298 |
299 | Action::value('update')->label('Update Selected')->group('Default Options')->callback(function ($mode, $items) {
300 | // $items contains an array with the primary keys of the selected items
301 | }),
302 |
303 | Action::groupBy('Export Options', function () {
304 | return [
305 | Action::value('csv')->label('Export CSV')->export('SalesOrders.csv'),
306 | Action::value('html')->label('Export HTML')->export('SalesOrders.html'),
307 | Action::value('xlsx')->label('Export XLSX')->export('SalesOrders.xlsx')->styles($this->exportStyles)->widths($this->exportWidths)
308 | ];
309 | }),
310 | ];
311 | }
312 | ```
313 |
314 | ### Mass Action Style
315 |
316 | If you only have small style adjustments to the Bulk Action Dropdown you can adjust some settings here:
317 |
318 | ```php
319 | public function getExportStylesProperty()
320 | {
321 | return [
322 | '1' => ['font' => ['bold' => true]],
323 | 'B2' => ['font' => ['italic' => true]],
324 | 'C' => ['font' => ['size' => 16]],
325 | ];
326 | }
327 |
328 | public function getExportWidthsProperty()
329 | {
330 | return [
331 | 'A' => 55,
332 | 'B' => 45,
333 | ];
334 | }
335 | ```
336 |
337 | ### Pin Records
338 |
339 | If you want to give your users the ability to pin specific records to be able to, for example, compare
340 | them with each other, you can use the CanPinRecords trait. Ensure to have at least one Checkbox Column
341 | so the user can select records:
342 |
343 | ```php
344 | use Mediconesystems\LivewireDatatables\Traits\CanPinRecords;
345 |
346 | class RecordTable extends LivewireDatatable
347 | {
348 | use CanPinRecords;
349 |
350 | public $model = Record::class;
351 |
352 | public function columns()
353 | {
354 | return [
355 | Column::checkbox(),
356 |
357 | // ...
358 |
359 | ```
360 |
361 | ### Custom column names
362 | 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:
363 |
364 | ```php
365 |
366 | public function builder()
367 | {
368 | return User::query()
369 | ->leftJoin('planets', 'planets.id', 'users.planet_id')
370 | ->leftJoin('moons', 'moons.id', 'planets.moon_id')
371 | ->groupBy('users.id');
372 | }
373 |
374 | public function columns()
375 | {
376 | return [
377 | NumberColumn::name('id')
378 | ->filterable(),
379 |
380 | Column::name('planets.name')
381 | ->label('Planet'),
382 |
383 | Column::raw('GROUP_CONCAT(planets.name SEPARATOR " | ") AS `Moon`'),
384 |
385 | ...
386 | }
387 |
388 | ```
389 |
390 | ### Callbacks
391 | Callbacks give you the freedom to perform any mutations you like on the data before displaying in the table.
392 | - The callbacks are performed on the paginated results of the database query, so shouldn't use a ton of memory
393 | - Callbacks will receive the chosen columns as their arguments.
394 | - 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.
395 | - If you want to format the result differently for export, use ```->exportCallback(Closure $callback)```.
396 | ```php
397 | class CallbackDemoTable extends LivewireDatatable
398 | {
399 | public $model = User::class
400 |
401 | public function columns()
402 | {
403 | return [
404 | Column::name('users.id'),
405 |
406 | Column::name('users.dob')->format(),
407 |
408 | Column::callback(['dob', 'signup_date'], function ($dob, $signupDate) {
409 | $age = $signupDate->diffInYears($dob);
410 | return $age > 18
411 | ? '' . $age . ''
412 | : $age;
413 | })->exportCallback(function ($dob, $signupDate), {
414 | return $age = $signupDate->diffInYears($dob);
415 | }),
416 |
417 | ...
418 | }
419 | }
420 | ```
421 |
422 | ### Default Filters
423 |
424 | If you want to have a default filter applied to your table, you can use the `defaultFilters` property. The `defaultFilter` 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.
425 |
426 | In the example below, the table will by default be filtered by rows where the _deleted_at_ column is false. If the user has a persisted filter for the _deleted_at_ column, the default filter will be ignored.
427 |
428 | ```php
429 | class CallbackDemoTable extends LivewireDatatable
430 | {
431 | public $defaultFilters = [
432 | 'deleted_at' => '0',
433 | ];
434 |
435 | public function builder()
436 | {
437 | return User::query()->withTrashed();
438 | }
439 |
440 | public function columns()
441 | {
442 | return [
443 | Column::name('id'),
444 | BooleanColumn::name('deleted_at')->filterable(),
445 | ];
446 | }
447 | }
448 | ```
449 |
450 | ### Views
451 | You can specify that a column's output is piped directly into a separate blade view template.
452 | - Template is specified using ususal laravel view helper syntax
453 | - Views will receive the column's value as ```$value```, and the whole query row as ```$row```
454 | ```php
455 | class CallbackDemoTable extends LivewireDatatable
456 | {
457 | public $model = User::class
458 |
459 | public function columns()
460 | {
461 | return [
462 | Column::name('users.id'),
463 |
464 | Column::name('users.dob')->view('tables.dateview'),
465 |
466 | Column::name('users.signup_date')->format(),
467 | ];
468 | }
469 | ```
470 | ```html
471 | 'tables/dateview.blade.php'
472 |
473 |
474 |
475 | ```
476 |
477 | ### Editable Columns
478 | You can mark a column as editable using ```editable```
479 | 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.
480 |
481 | ```php
482 | class EditableTable extends LivewireDatatable
483 | {
484 | public $model = User::class;
485 |
486 | public function columns()
487 | {
488 | return [
489 | Column::name('id')
490 | ->label('ID')
491 | ->linkTo('job', 6),
492 |
493 | Column::name('email')
494 | ->editable(),
495 |
496 | ...
497 | ];
498 | }
499 | }
500 | ```
501 |
502 | # Complex Query Builder
503 | Just add ```$complex = true``` to your Datatable Class and all filterable columns will be available in the complex query builder.
504 |
505 | **Features**
506 | - Combine rules and groups of rules using AND/OR logic
507 | - Drag and drop rules around the interface
508 |
509 | 
510 | ---
511 | **Persisting Queries** (Requires AlpineJS v3 with $persist plugin)
512 | - Add ```$persistComplexQuery = true``` to your class and queries will be stored in browser localstorage.
513 | - By default the localstorage key will be the class name. You can provide your own by setting the public property ```$persistKey``` or overriding ```getPersistKeyProperty()``` on the Datatable Class
514 | - eg: for user-specific persistence:
515 |
516 | ```php
517 | public function getPersistKeyProperty()
518 | {
519 | return Auth::id() . '-' . parent::getPersistKeyProperty();
520 | }
521 | ```
522 | ---
523 | **Saving Queries**
524 |
525 | 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:
526 |
527 | - ```public function saveQuery(String $name, Array $rules)```
528 | - ```public function deleteQuery(Int $id)```
529 | - ```public function getSavedQueries()```
530 |
531 | * In your save and delete methods, be sure to emit an ```updateSavedQueries``` livewire event and pass a fresh array of results (see example below)
532 |
533 | ### Example:
534 | This example shows saving queries using a conventional Laravel ComplexQuery model, that belongsTo a User
535 |
536 | ```php
537 | /* Migration */
538 |
539 | class CreateComplexQueriesTable extends Migration
540 | {
541 | public function up()
542 | {
543 | Schema::create('complex_queries', function (Blueprint $table) {
544 | $table->id();
545 | $table->unsignedInteger('user_id');
546 | $table->string('table');
547 | $table->json('rules');
548 | $table->string('name');
549 | $table->timestamps();
550 | });
551 | }
552 | }
553 |
554 |
555 | /* Model */
556 |
557 | class ComplexQuery extends BaseModel
558 | {
559 | protected $casts = ['rules' => 'array'];
560 |
561 | public function user()
562 | {
563 | return $this->belongsTo(User::class);
564 | }
565 | }
566 |
567 | /* Datatable Class */
568 |
569 | class TableWithSaving extends LivewireDatatable
570 | {
571 | ...
572 |
573 | public function saveQuery($name, $rules)
574 | {
575 | Auth::user()->complex_queries()->create([
576 | 'table' => $this->name,
577 | 'name' => $name,
578 | 'rules' => $rules
579 | ]);
580 |
581 | $this->emit('updateSavedQueries', $this->getSavedQueries());
582 | }
583 |
584 | public function deleteQuery($id)
585 | {
586 | ComplexQuery::destroy($id);
587 |
588 | $this->emit('updateSavedQueries', $this->getSavedQueries());
589 | }
590 |
591 | public function getSavedQueries()
592 | {
593 | return Auth::user()->complex_queries()->where('table', $this->name)->get();
594 | }
595 |
596 | ...
597 | }
598 | ```
599 |
600 |
601 | # Styling
602 | 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.
603 |
604 | There are methods for applying styles to rows and cells. ```rowClasses``` receives the ```$row``` and the [laravel loop variable](https://laravel.com/docs/8.x/blade#the-loop-variable) as parameters. ```cellClasses``` receives the ```$row``` and ```$column```
605 |
606 | For example:
607 | ```php
608 | public function rowClasses($row, $loop)
609 | {
610 | 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')));
611 | }
612 |
613 | public function cellClasses($row, $column)
614 | {
615 | return 'text-sm ' . ($this->rowIsSelected($row) ? ' text-gray-900' : ($row->{'car.model'} === 'Ferrari' ? ' text-white' : ' text-gray-900'));
616 | }
617 | ```
618 |
619 | 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.
620 |
621 | You could also override the render method in your table's class to provide different templates for different tables.
622 |
623 |
624 | ## Credits and Influences
625 | - [Laravel](https://laravel.com/)
626 | - [Laravel Livewire](https://laravel-livewire.com/docs/quickstart/)
627 | - [Tailwind CSS](https://tailwindcss.com/)
628 | - [AlpineJS](https://github.com/alpinejs/alpine)
629 | - [livewire-tables by coryrose1](https://github.com/coryrose1/livewire-tables)
630 | - [laravel-livewire-datatables by kdion4891](https://github.com/kdion4891/laravel-livewire-tables)
631 | - [Jonathan Reinink\'s Eloquent course](https://eloquent-course.reinink.ca/)
632 |
--------------------------------------------------------------------------------