diff --git a/add-column.md b/add-column.md index 01dcaf3..55191fd 100644 --- a/add-column.md +++ b/add-column.md @@ -1,12 +1,14 @@ # Add Column -You can add a custom column on your response by using `addColumn` api. +You can add a custom column to your response by using the `addColumn` api. + +> {note} added columns are assumed to be computed columns and not part of the database. Thus, search/sort will be disabled for those columns. If you need them, use the `editColumn` api instead. ## Add Column with Blade Syntax ```php -use DataTables; +use Yajra\DataTables\Facades\DataTables; Route::get('user-data', function() { $model = App\User::query(); @@ -21,7 +23,7 @@ Route::get('user-data', function() { ## Add Column with Closure ```php -use DataTables; +use Yajra\DataTables\Facades\DataTables; Route::get('user-data', function() { $model = App\User::query(); @@ -40,7 +42,7 @@ Route::get('user-data', function() { > {tip} You can use view to render your added column by passing the view path as the second argument on `addColumn` api. ```php -use DataTables; +use Yajra\DataTables\Facades\DataTables; Route::get('user-data', function() { $model = App\User::query(); @@ -62,7 +64,7 @@ Hi {{ $name }}! > {tip} Just pass the column order as the third argument of `addColumn` api. ```php -use DataTables; +use Yajra\DataTables\Facades\DataTables; Route::get('user-data', function() { $model = App\User::query(); diff --git a/buttons-config.md b/buttons-config.md index 5b4260d..817b62e 100644 --- a/buttons-config.md +++ b/buttons-config.md @@ -12,8 +12,8 @@ Namespace configuration is used by the datatables command generator. ``` ### DataTable Base Namespace/Directory -This is the base namespace/directory to be created when a new DataTable was called. -This directory is appended on default Laravel namespace. +This is the base namespace/directory to be created when a new DataTable is called. +This directory is appended to the default Laravel namespace. **Usage:** ```php artisan datatables:make User``` @@ -24,8 +24,8 @@ This directory is appended on default Laravel namespace. **Export filename:** ```users_(timestamp)``` ### Model Option -This is the base namespace/directory where your model's are located. -This directory is appended on default Laravel namespace. +This is the base namespace/directory where your models are located. +This directory is appended to the default Laravel namespace. **Usage:** ```php artisan datatables:make Post --model``` **Output:** ```App\DataTables\PostDataTable``` **With Model:** ```App\Post`` @@ -33,7 +33,7 @@ This directory is appended on default Laravel namespace. ## PDF Generator -Set the PDF generator to be used when converting your dataTable to pdf. +Set the PDF generator to be used when converting your dataTable to PDF. Available generators are: `excel`, `snappy` diff --git a/buttons-console.md b/buttons-console.md index 7e88422..0efc0fc 100644 --- a/buttons-console.md +++ b/buttons-console.md @@ -18,7 +18,7 @@ In this example, we will create a DataTable service class. php artisan datatables:make Posts ``` -This will create an `PostsDataTable` class on `app\DataTables` directory. +This will create a `PostsDataTable` class in the `app\DataTables` directory. ```php namespace App\DataTables; @@ -101,7 +101,7 @@ In this example, we will pass a `--model` option to set the model to be used by php artisan datatables:make Posts --model ``` -This will generate a `App\DataTables\PostsDataTable` class that uses `App\Post` as the base model for our query. +This will generate an `App\DataTables\PostsDataTable` class that uses `App\Post` as the base model for our query. The exported filename will also be set to `posts_(timestamp)`. ```php @@ -194,12 +194,12 @@ This will allow to use a non-standard namespace if front-end and back-end models ### Action Option -In this example, we will pass a `--action` option to set a custom path for the action column view. +In this example, we will use the `--action` option to set a custom path for the action column view. ``` php artisan datatables:make Posts --action="client.action" ``` -If not provided, a default path will be used. It will needs to be changed thereafter. +If no path is provided, a default path will be used. It will need to be changed thereafter. ### Columns Option @@ -208,13 +208,13 @@ In this example, we will pass a `--columns` option to set the columns to be used ``` php artisan datatables:make Posts --columns="id,title,author" ``` -If not provided, a default set of columns will be used. It will needs to be manually changed thereafter. +If not provided, a default set of columns will be used. It will need to be manually changed thereafter. ## Creating a DataTable Scope service class -DataTable scope is class that we can use to limit our database search results based on the defined query scopes. +DataTable scope is a class that we can use to limit our database search results based on the defined query scopes. ``` php artisan datatables:scope ActiveUser diff --git a/buttons-custom.md b/buttons-custom.md index 9330875..089a318 100644 --- a/buttons-custom.md +++ b/buttons-custom.md @@ -1,9 +1,9 @@ # Custom Actions -You can enable custom actions on your buttons, as follows: +You can enable custom actions on your buttons as follows: Update `UsersDataTable` class and overload the `actions` property. Here we are -disabling the `csv` and `pdf` action (so they cannot be fired by hijacking the +disabling the `csv` and `pdf` actions (so they cannot be fired by hijacking their request) and enabling a `myCustomAction`. @@ -15,7 +15,7 @@ use Yajra\DataTables\Services\DataTable; class UsersDataTable extends DataTable { - protected $actions = ['print', 'excel', 'myCustomAction']; + protected array $actions = ['print', 'excel', 'myCustomAction']; public function html() { diff --git a/buttons-fast-excel.md b/buttons-fast-excel.md new file mode 100644 index 0000000..4d0819e --- /dev/null +++ b/buttons-fast-excel.md @@ -0,0 +1,62 @@ +# Fast Excel Integration + +[Fast-Excel](https://github.com/rap2hpoutre/fast-excel) is recommended when exporting bulk records. + +## LIMITATIONS! + +FastExcel integration uses cursor behind the scene thus eager loaded columns will not work on export. You MUST use join statements if you want to export related columns. Also, column value formatting like converting boolean to Yes or No should be done on SQL LEVEL. + +## Usage + +1. Install `fast-excel` using `composer require rap2hpoutre/fast-excel`. +2. Create a dataTable class `php artisan datatables:make Users`. +3. Adjust `UsersDataTable` as needed. +4. Set property `$fastExcel = true`. + +```php +class UsersDataTable extends DataTable +{ + protected bool $fastExcel = true; + + ... +} +``` + +5. DataTables will now export csv & excel using `fast-excel` package. + + +## Faster export by disabling the fast-excel callback + +1. Just set property `$fastExcelCallback = false`. This is enabled by default for a better formatted output of exported file. + +```php +class UsersDataTable extends DataTable +{ + protected bool $fastExcel = true; + protected bool $fastExcelCallback = false; + +``` + +2. The exported file will now be based on your query's structure. No header formatting and all selected columns in sql will be included in the output. + +## Using custom callback + +Just override the `fastExcelCallback` method: + +```php +class UsersDataTable extends DataTable +{ + protected bool $fastExcel = true; + + public function fastExcelCallback() \Closure + { + return function ($row) { + return [ + 'Name' => $row['name'], + 'Email' => $row['email'], + ]; + }; + } + +... +``` diff --git a/buttons-installation.md b/buttons-installation.md index 87e80a8..b6aec3e 100644 --- a/buttons-installation.md +++ b/buttons-installation.md @@ -1,11 +1,20 @@ -# Buttons Plugin Installation +# Buttons Plugin + +A Laravel DataTables plugin for handling server-side exporting of table as csv, excel, pdf, etc. + + +## Installation Run the following command in your project to get the latest version of the plugin: -`composer require yajra/laravel-datatables-buttons:^3.0` +```bash +composer require yajra/laravel-datatables-buttons:"^12.0" +``` + ## Configuration -> This step is optional if you are using Laravel 5.5 + +> This step is optional if you are using Laravel 5.5+ Open the file ```config/app.php``` and then add following service provider. @@ -19,6 +28,6 @@ Open the file ```config/app.php``` and then add following service provider. After completing the step above, use the following command to publish configuration & assets: -``` +```bash php artisan vendor:publish --tag=datatables-buttons ``` diff --git a/buttons-laravel-excel.md b/buttons-laravel-excel.md new file mode 100644 index 0000000..3756cb3 --- /dev/null +++ b/buttons-laravel-excel.md @@ -0,0 +1,59 @@ +# Laravel Excel Integration + +[Laravel Excel](https://github.com/Maatwebsite/Laravel-Excel) is the default package used when exporting DataTables to Excel and CSV. + +## Using Export Class + +1. Create an export class `php artisan make:export UsersExport` +2. Update the generated export class and extend `DataTablesCollectionExport` + +```php +namespace App\Exports; + +use Yajra\DataTables\Exports\DataTablesCollectionExport; + +class UsersExport extends DataTablesCollectionExport +{ + +} +``` + +3. Update your `UsersDataTable` class and set `protected $exportClass = UsersExport::class` + +```php +class UsersDataTable extends DataTable +{ + protected $exportClass = UsersExport::class; + +``` + +4. Update your export class as needed. See official package docs: https://docs.laravel-excel.com/3.1/exports/collection.html + +## Example Export Class + +```php +namespace App\Exports; + +use Maatwebsite\Excel\Concerns\WithMapping; +use Yajra\DataTables\Exports\DataTablesCollectionExport; + +class UsersExport extends DataTablesCollectionExport implements WithMapping +{ + public function headings(): array + { + return [ + 'Name', + 'Email', + ]; + } + + public function map($row): array + { + return [ + $row['name'], + $row['email'], + ]; + } +} +``` + diff --git a/documentation.md b/documentation.md index cf92ae2..14788f5 100644 --- a/documentation.md +++ b/documentation.md @@ -2,18 +2,15 @@ - [Release Notes](/docs/{{package}}/{{version}}/releases) - [Upgrade Guide](/docs/{{package}}/{{version}}/upgrade) - [Contribution Guide](/docs/{{package}}/{{version}}/contributing) - - [Security Issues](/docs/{{package}}/{{version}}/security) - - [API Documentation](http://yajra.github.io/{{package}}/api/{{version}}) + - [Security Issues](/docs/{{package}}/{{version}}/security) - ## Getting Started - [Introduction](/docs/{{package}}/{{version}}/introduction) - - [Installation](/docs/{{package}}/{{version}}/installation) - - [Demo Application](https://datatables.yajrabox.com/) + - [Installation](/docs/{{package}}/{{version}}/installation) - [Community Links](/docs/{{package}}/{{version}}/community-links) - ## Tutorials - - [Quick Starter](/docs/{{package}}/{{version}}/quick-starter) - - [Service Implementation](https://datatables.yajrabox.com/service) + - [Quick Starter](/docs/{{package}}/{{version}}/quick-starter) - ## Configuration - [General Settings](/docs/{{package}}/{{version}}/general-settings) @@ -28,8 +25,6 @@ - ## Response - [Array Response](/docs/{{package}}/{{version}}/response-array) - [Object Response](/docs/{{package}}/{{version}}/response-object) - - [Fractal Transformer](/docs/{{package}}/{{version}}/response-fractal) - - [Fractal Serializer](/docs/{{package}}/{{version}}/response-fractal-serializer) - [Additional Data Response](/docs/{{package}}/{{version}}/response-with) - [Only Columns](/docs/{{package}}/{{version}}/response-only) - [Response Resource](/docs/{{package}}/{{version}}/response-resource) @@ -41,8 +36,8 @@ - [Remove Column](/docs/{{package}}/{{version}}/remove-column) - [Index Column](/docs/{{package}}/{{version}}/index-column) - [Raw Columns](/docs/{{package}}/{{version}}/raw-columns) - - [Export Columns](/docs/{{package}}/{{version}}/export-columns) - - [Print Columns](/docs/{{package}}/{{version}}/print-columns) + - [Export Columns](/docs/{{package}}/{{version}}/export-column) + - [Print Columns](/docs/{{package}}/{{version}}/print-column) - ## Row Editing - [Row Options](/docs/{{package}}/{{version}}/row-options) @@ -65,6 +60,11 @@ - [Order Columns](/docs/{{package}}/{{version}}/order-columns) - [Order By Nulls Last](/docs/{{package}}/{{version}}/order-by-nulls-last) +- ## SearchPanes + - [SearchPanes Extension](/docs/{{package}}/{{version}}/search-panes-starter) + - [Hide Columns in SearchPanes](/docs/{{package}}/{{version}}/search-panes-hide-columns) + - [Further options](/docs/{{package}}/{{version}}/search-panes-options) + - ## Utilities - [XSS filtering](/docs/{{package}}/{{version}}/xss) - [Blacklist Columns](/docs/{{package}}/{{version}}/blacklist) @@ -76,41 +76,54 @@ ### PLUGINS -- ## HTML Builder - - [Installation](/docs/{{package}}/{{version}}/html-installation) - - [Builder](/docs/{{package}}/{{version}}/html-builder) - - [Table](/docs/{{package}}/{{version}}/html-builder-table) - - [Config](/docs/{{package}}/{{version}}/html-builder-config) - - [Columns](/docs/{{package}}/{{version}}/html-builder-column) - - [Column Builder](/docs/{{package}}/{{version}}/html-builder-column-builder) - - [Macro](/docs/{{package}}/{{version}}/html-builder-macro) - - [Ajax](/docs/{{package}}/{{version}}/html-builder-ajax) - - [Minified Ajax](/docs/{{package}}/{{version}}/html-builder-minified-ajax) - - [Post Ajax](/docs/{{package}}/{{version}}/html-builder-post-ajax) - - [Parameters](/docs/{{package}}/{{version}}/html-builder-parameters) - - [Events/Callbacks](/docs/{{package}}/{{version}}/html-builder-callbacks) - - [Add Action](/docs/{{package}}/{{version}}/html-builder-action) - - [Add Checkbox](/docs/{{package}}/{{version}}/html-builder-checkbox) - - [Add Index](/docs/{{package}}/{{version}}/html-builder-index) - - [Github](https://github.com/yajra/laravel-datatables-html) +- ## Html + - [Installation](/docs/{{package}}/{{version}}/html-installation) + - [Builder](/docs/{{package}}/{{version}}/html-builder) + - [Table](/docs/{{package}}/{{version}}/html-builder-table) + - [Config](/docs/{{package}}/{{version}}/html-builder-config) + - [Columns](/docs/{{package}}/{{version}}/html-builder-column) + - [Column Builder](/docs/{{package}}/{{version}}/html-builder-column-builder) + - [Macro](/docs/{{package}}/{{version}}/html-builder-macro) + - [Ajax](/docs/{{package}}/{{version}}/html-builder-ajax) + - [Minified Ajax](/docs/{{package}}/{{version}}/html-builder-minified-ajax) + - [Post Ajax](/docs/{{package}}/{{version}}/html-builder-post-ajax) + - [Parameters](/docs/{{package}}/{{version}}/html-builder-parameters) + - [Events/Callbacks](/docs/{{package}}/{{version}}/html-builder-callbacks) + - [Add Action](/docs/{{package}}/{{version}}/html-builder-action) + - [Add Checkbox](/docs/{{package}}/{{version}}/html-builder-checkbox) + - [Add Index](/docs/{{package}}/{{version}}/html-builder-index) + - [Github](https://github.com/yajra/laravel-datatables-html) - ## Buttons - - [Installation](/docs/{{package}}/{{version}}/buttons-installation) - - [Configuration](/docs/{{package}}/{{version}}/buttons-config) - - [Quick Starter](/docs/{{package}}/{{version}}/buttons-starter) - - [DataTable Buttons](/docs/{{package}}/{{version}}/buttons-export) - - [Custom Actions](/docs/{{package}}/{{version}}/buttons-custom) - - [Sending Parameters](/docs/{{package}}/{{version}}/buttons-with) - - [Extended DataTable](/docs/{{package}}/{{version}}/buttons-extended) - - [Buttons Command](/docs/{{package}}/{{version}}/buttons-console) - - [Github](https://github.com/yajra/laravel-datatables-buttons) + - [Installation](/docs/{{package}}/{{version}}/buttons-installation) + - [Configuration](/docs/{{package}}/{{version}}/buttons-config) + - [Quick Starter](/docs/{{package}}/{{version}}/buttons-starter) + - [DataTable Buttons](/docs/{{package}}/{{version}}/buttons-export) + - [Custom Actions](/docs/{{package}}/{{version}}/buttons-custom) + - [Sending Parameters](/docs/{{package}}/{{version}}/buttons-with) + - [Extended DataTable](/docs/{{package}}/{{version}}/buttons-extended) + - [Buttons Command](/docs/{{package}}/{{version}}/buttons-console) + - [Laravel Excel Export](/docs/{{package}}/{{version}}/buttons-laravel-excel) + - [Fast Excel Export](/docs/{{package}}/{{version}}/buttons-fast-excel) + - [Github](https://github.com/yajra/laravel-datatables-buttons) + +- ## Fractal + - [Installation](/docs/{{package}}/{{version}}/fractal-installation) + - [Fractal Transformer](/docs/{{package}}/{{version}}/response-fractal) + - [Fractal Serializer](/docs/{{package}}/{{version}}/response-fractal-serializer) + +- ## Export + - [Installation](/docs/{{package}}/{{version}}/exports-installation) + - [Usage](/docs/{{package}}/{{version}}/exports-usage) + - [Purge](/docs/{{package}}/{{version}}/exports-purge) + - [Options](/docs/{{package}}/{{version}}/exports-options) - ## Editor - - [Installation](/docs/{{package}}/{{version}}/editor-installation) - - [Editor Command](/docs/{{package}}/{{version}}/editor-command) - - [Editor Model](/docs/{{package}}/{{version}}/editor-model) - - [Editor Rules](/docs/{{package}}/{{version}}/editor-rules) - - [Event Hooks](/docs/{{package}}/{{version}}/editor-events) - - [Usage](/docs/{{package}}/{{version}}/editor-usage) - - [Tutorial](/docs/{{package}}/{{version}}/editor-tutorial) - - [Github](https://github.com/yajra/laravel-datatables-editor) + - [Installation](/docs/{{package}}/{{version}}/editor-installation) + - [Editor Command](/docs/{{package}}/{{version}}/editor-command) + - [Editor Model](/docs/{{package}}/{{version}}/editor-model) + - [Editor Rules](/docs/{{package}}/{{version}}/editor-rules) + - [Event Hooks](/docs/{{package}}/{{version}}/editor-events) + - [Usage](/docs/{{package}}/{{version}}/editor-usage) + - [Tutorial](/docs/{{package}}/{{version}}/editor-tutorial) + - [Github](https://github.com/yajra/laravel-datatables-editor) diff --git a/editor-installation.md b/editor-installation.md index c4c95b6..7bed304 100644 --- a/editor-installation.md +++ b/editor-installation.md @@ -11,14 +11,16 @@ A [premium license](https://editor.datatables.net/purchase/index) is required to Run the following command in your project to get the latest version of the plugin: -`composer require yajra/laravel-datatables-editor:^1.0` +```bash +composer require yajra/laravel-datatables-editor:"^12.0" +``` ## Configuration > This step is optional if you are using Laravel 5.5 -Open the file ```config/app.php``` and then add following service provider. +Open the file ```config/app.php``` and then add the following service provider. ```php 'providers' => [ diff --git a/editor-tutorial.md b/editor-tutorial.md index cf453b2..caff59b 100644 --- a/editor-tutorial.md +++ b/editor-tutorial.md @@ -1,15 +1,11 @@ -# Creating a Laravel Full CRUD with DataTables Editor. +# Laravel 10 CRUD with DataTables Editor. Before we begin, please be reminded that the Editor library that we are going to use here requires a paid license. See [DataTables Editor](https://editor.datatables.net/purchase/index) for details. ## Pre-requisites -This tutorial requires https://yajrabox.com/docs/laravel-datatables/master/quick-starter. - -## Install DataTables Editor assets. - - yarn add datatables.net-editor datatables.net-editor-bs4 datatables.net-select-bs4 +This tutorial requires https://yajrabox.com/docs/laravel-datatables/10.0/quick-starter. ## Editor License @@ -17,107 +13,162 @@ Copy and rename your `Editor.XX.zip` to `Editor.zip` and move it to project fold ## Register postinstall script to package.json +```json "scripts": { - "postinstall": "node ./node_modules/datatables.net-editor/install.js ./Editor.zip", - "dev": "npm run development", - ..... + "dev": "vite", + "build": "vite build", + "postinstall": "node node_modules/datatables.net-editor/install.js ./Editor.zip" }, +``` -## Register editor script on `resources/js/bootstrap.js` - - try { - window.Popper = require('popper.js').default; - window.$ = window.jQuery = require('jquery'); - - require('bootstrap'); - require('datatables.net-bs4'); - require('datatables.net-buttons-bs4'); - require('datatables.net-select-bs4'); - require('datatables.net-editor-bs4'); - } catch (e) {} +## Install DataTables Editor assets. +```sh +npm i datatables.net-editor datatables.net-editor-bs5 +``` -## Add editor styles on `resources/sass/app.scss`. +## Register editor script on `resources/js/app.js` - @import "~datatables.net-select-bs4/css/select.bootstrap4.css"; - @import "~datatables.net-editor-bs4/css/editor.bootstrap4.css"; +```js +import './bootstrap'; +import 'laravel-datatables-vite'; -## Recompile assets. +import "datatables.net-editor"; +import Editor from "datatables.net-editor-bs5"; +Editor(window, $); +``` - yarn - yarn watch / dev / prod +## Add editor styles on `resources/sass/app.scss`. +```css +// Fonts +@import url('https://fonts.bunny.net/css?family=Nunito'); -## Update UsersDataTable and register the Editor buttons. +// Variables +@import 'variables'; -> Note: CREATE button is in conflict with `buttons.server-side.js`. You need to remove the create button or rename it to something else like `add` button. +// Bootstrap +@import 'bootstrap/scss/bootstrap'; - DataTable.ext.buttons.add = { - className: 'buttons-add', +// DataTables +@import 'bootstrap-icons/font/bootstrap-icons.css'; +@import "datatables.net-bs5/css/dataTables.bootstrap5.css"; +@import "datatables.net-buttons-bs5/css/buttons.bootstrap5.css"; +@import "datatables.net-editor-bs5/css/editor.bootstrap5.css"; +@import 'datatables.net-select-bs5/css/select.bootstrap5.css'; +``` - text: function (dt) { - return ' ' + dt.i18n('buttons.add', 'Create'); - }, +## Recompile assets. - action: function (e, dt, button, config) { - window.location = window.location.href.replace(/\/+$/, "") + '/create'; - } - }; +```sh +npm run dev +``` ### UsersDataTable.php Create a new editor instance and add some fields for name and email. ```php +namespace App\DataTables; + +use App\Models\User; +use Illuminate\Database\Eloquent\Builder as QueryBuilder; +use Yajra\DataTables\EloquentDataTable; +use Yajra\DataTables\Html\Builder as HtmlBuilder; +use Yajra\DataTables\Html\Button; +use Yajra\DataTables\Html\Column; use Yajra\DataTables\Html\Editor\Editor; use Yajra\DataTables\Html\Editor\Fields; +use Yajra\DataTables\Services\DataTable; -... +class UsersDataTable extends DataTable +{ /** * Build DataTable class. * - * @param mixed $query Results from query() method. - * @return \Yajra\DataTables\DataTableAbstract + * @param QueryBuilder $query Results from query() method. + * @return \Yajra\DataTables\EloquentDataTable */ - public function dataTable($query) + public function dataTable(QueryBuilder $query): EloquentDataTable { - return datatables() - ->eloquent($query) - ->setRowId('id') // Set the RowID - ... + return (new EloquentDataTable($query))->setRowId('id'); } - public function html() + /** + * Get query source of dataTable. + * + * @param \App\Models\User $model + * @return \Illuminate\Database\Eloquent\Builder + */ + public function query(User $model): QueryBuilder + { + return $model->newQuery(); + } + + /** + * Optional method if you want to use html builder. + * + * @return \Yajra\DataTables\Html\Builder + */ + public function html(): HtmlBuilder { return $this->builder() ->setTableId('users-table') ->columns($this->getColumns()) ->minifiedAjax() - ->dom('Bfrtip') ->orderBy(1) - ->buttons( + ->selectStyleSingle() + ->editors([ + Editor::make() + ->fields([ + Fields\Text::make('name'), + Fields\Text::make('email'), + ]), + ]) + ->buttons([ Button::make('create')->editor('editor'), Button::make('edit')->editor('editor'), Button::make('remove')->editor('editor'), - Button::make('export'), + Button::make('excel'), + Button::make('csv'), + Button::make('pdf'), Button::make('print'), Button::make('reset'), - Button::make('reload') - ) - ->editor( - Editor::make() - ->fields([ - Fields\Text::make('name'), - Fields\Text::make('email'), - Fields\Password::make('password'), - ]) - ); + Button::make('reload'), + ]); + } + + /** + * Get the dataTable columns definition. + * + * @return array + */ + public function getColumns(): array + { + return [ + Column::make('id'), + Column::make('name'), + Column::make('email'), + Column::make('created_at'), + Column::make('updated_at'), + ]; + } + + /** + * Get filename for export. + * + * @return string + */ + protected function filename(): string + { + return 'Users_'.date('YmdHis'); } +} ``` ## Create Editor Class to handle CRUD actions. -``` +```sh php artisan datatables:editor Users ``` @@ -125,13 +176,14 @@ php artisan datatables:editor Users Edit `routes/web.php` and register the store user route. -``` -Route::post('/users', 'UsersController@store')->name('users.store'); +```php +Route::get('/users', [App\Http\Controllers\UsersController::class, 'index'])->name('users.index'); +Route::post('/users', [App\Http\Controllers\UsersController::class, 'store'])->name('users.store'); ``` ## Update users controller -``` +```php namespace App\Http\Controllers; use Illuminate\Http\Request; diff --git a/engine-collection.md b/engine-collection.md index 3b8bed0..418ccc4 100644 --- a/engine-collection.md +++ b/engine-collection.md @@ -1,7 +1,7 @@ # Collection Data Source You may use Laravel's Collection as data source for your dataTables. -You can look at `Yajra\DataTables\CollectionDataTable` class which handles the conversion of your Collection into a readbale DataTable API response. +You can look at `Yajra\DataTables\CollectionDataTable` class which handles the conversion of your Collection into a readable DataTable API response. ## Collection via Factory diff --git a/engine-eloquent.md b/engine-eloquent.md index e2874c9..f68e4d0 100644 --- a/engine-eloquent.md +++ b/engine-eloquent.md @@ -1,7 +1,7 @@ # Eloquent Data Source You may use Laravel's Eloquent Model as data source for your dataTables. -You can look at `Yajra\DataTables\EloquentDataTable` class which handles the conversion of your Eloquent Model into a readbale DataTable API response. +You can look at `Yajra\DataTables\EloquentDataTable` class which handles the conversion of your Eloquent Model into a readable DataTable API response. ## Eloquent via Factory diff --git a/engine-query.md b/engine-query.md index 4d2c09d..700e6e9 100644 --- a/engine-query.md +++ b/engine-query.md @@ -1,7 +1,7 @@ # Query Builder Data Source You may use Laravel's Query Builder as data source for your dataTables. -You can look at `Yajra\DataTables\QueryDataTable` class which handles the conversion of your Query Builder into a readbale DataTable API response. +You can look at `Yajra\DataTables\QueryDataTable` class which handles the conversion of your Query Builder into a readable DataTable API response. ## Query Builder via Factory @@ -27,7 +27,7 @@ use DataTables; Route::get('user-data', function() { $query = DB::table('users'); - return DataTables::queryBuilder($query)->toJson(); + return DataTables::query($query)->toJson(); }); ``` @@ -41,7 +41,7 @@ use Yajra\DataTables\DataTables; Route::get('user-data', function(DataTables $dataTables) { $query = DB::table('users'); - return $dataTables->queryBuilder($query)->toJson(); + return $dataTables->query($query)->toJson(); }); ``` @@ -53,7 +53,7 @@ use DB; Route::get('user-data', function() { $query = DB::table('users'); - return app('datatables')->queryBuilder($query)->toJson(); + return app('datatables')->query($query)->toJson(); }); ``` diff --git a/exports-installation.md b/exports-installation.md new file mode 100644 index 0000000..59afb4e --- /dev/null +++ b/exports-installation.md @@ -0,0 +1,30 @@ +# Export Plugin Installation + +Github: https://github.com/yajra/laravel-datatables-export + +This package is a plugin of Laravel DataTables for handling server-side exporting using Queue, OpenSpout and Livewire. + +## Quick Installation + +``` +composer require yajra/laravel-datatables-export:"^12.0" +``` + +The package also requires batch job: + +``` +php artisan queue:batches-table +php artisan migrate +``` + +## Service Provider (Optional since Laravel 5.5+) + +``` +Yajra\DataTables\ExportServiceProvider::class +``` + +## Configuration and Assets (Optional) + +``` +$ php artisan vendor:publish --tag=datatables-export --force +``` diff --git a/exports-options.md b/exports-options.md new file mode 100644 index 0000000..895d397 --- /dev/null +++ b/exports-options.md @@ -0,0 +1,98 @@ +# Export Options + +## Export Type + +You can set the export type by setting the property to `csv` or `xlsx`. Default value is `xlsx`. + +```php + + +``` + +## Set Excel Sheet Name + +Option 1: You can set the Excel sheet name by setting the property. + +```php + +``` + +Option 2: You can also set the Excel sheet name by overwriting the method. + +```php +protected function sheetName() : string +{ + return "Yearly Report"; +} +``` + +## Formatting Columns + +You can format the column by setting it via Column definition on you DataTable service class. + +```php +Column::make('mobile')->exportFormat('00000000000'), +``` + +The format above will treat mobile numbers as text with leading zeroes. + +## Numeric Fields Formatting + +The package will auto-detect numeric fields and can be used with custom formats. + +```php +Column::make('total')->exportFormat('0.00'), +Column::make('count')->exportFormat('#,##0'), +Column::make('average')->exportFormat('#,##0.00'), +``` + +## Date Fields Formatting + +The package will auto-detect date fields when used with a valid format or is a DateTime instance. + +```php +Column::make('report_date')->exportFormat('mm/dd/yyyy'), +Column::make('created_at'), +Column::make('updated_at')->exportFormat(NumberFormat::FORMAT_DATE_DATETIME), +``` + +## Valid Date Formats + +Valid date formats can be adjusted on `datatables-export.php` config file. + +```php + 'date_formats' => [ + 'mm/dd/yyyy', + NumberFormat::FORMAT_DATE_DATETIME, + NumberFormat::FORMAT_DATE_YYYYMMDD, + NumberFormat::FORMAT_DATE_XLSX22, + NumberFormat::FORMAT_DATE_DDMMYYYY, + NumberFormat::FORMAT_DATE_DMMINUS, + NumberFormat::FORMAT_DATE_DMYMINUS, + NumberFormat::FORMAT_DATE_DMYSLASH, + NumberFormat::FORMAT_DATE_MYMINUS, + NumberFormat::FORMAT_DATE_TIME1, + NumberFormat::FORMAT_DATE_TIME2, + NumberFormat::FORMAT_DATE_TIME3, + NumberFormat::FORMAT_DATE_TIME4, + NumberFormat::FORMAT_DATE_TIME5, + NumberFormat::FORMAT_DATE_TIME6, + NumberFormat::FORMAT_DATE_TIME7, + NumberFormat::FORMAT_DATE_XLSX14, + NumberFormat::FORMAT_DATE_XLSX15, + NumberFormat::FORMAT_DATE_XLSX16, + NumberFormat::FORMAT_DATE_XLSX17, + NumberFormat::FORMAT_DATE_YYYYMMDD2, + NumberFormat::FORMAT_DATE_YYYYMMDDSLASH, + ] +``` + +## Force Numeric Field As Text Format + +Option to force auto-detected numeric value as text format. + +```php +Column::make('id')->exportFormat('@'), +Column::make('id')->exportFormat(NumberFormat::FORMAT_GENERAL), +Column::make('id')->exportFormat(NumberFormat::FORMAT_TEXT), +``` diff --git a/exports-purge.md b/exports-purge.md new file mode 100644 index 0000000..ee246f1 --- /dev/null +++ b/exports-purge.md @@ -0,0 +1,9 @@ +# Export Usage + +## Purging exported files + +On `app\Console\Kernel.php`, register the purge command + +```php +$schedule->command('datatables:purge-export')->weekly(); +``` diff --git a/exports-usage.md b/exports-usage.md new file mode 100644 index 0000000..f5d6a29 --- /dev/null +++ b/exports-usage.md @@ -0,0 +1,24 @@ +# Export Usage + +## Usage + +1. Add the export-button livewire component on your view file that uses dataTable class. + +```php + +``` + +2. On your `DataTable` class, use `WithExportQueue` + +```php +use Yajra\DataTables\WithExportQueue; + +class PermissionsDataTable extends DataTable +{ + use WithExportQueue; + + ... +} +``` + +3. Run your queue worker. Ex: `php artisan queue:work` diff --git a/filter-column.md b/filter-column.md index a0e9f88..81e4734 100644 --- a/filter-column.md +++ b/filter-column.md @@ -4,11 +4,12 @@ In some cases, we need to implement a custom search for a specific column. To achieve this, you can use `filterColumn` api. ```php -use DataTables; -use DB; +use Yajra\DataTables\Facades\DataTables; +use Illuminate\Support\Facades\DB; +use App\User; Route::get('user-data', function() { - $model = App\User::select([ + $model = User::query()->select([ 'id', DB::raw("CONCAT(users.first_name,'-',users.last_name) as fullname"), 'email', diff --git a/fractal-installation.md b/fractal-installation.md new file mode 100644 index 0000000..e717b4d --- /dev/null +++ b/fractal-installation.md @@ -0,0 +1,28 @@ +# Fractal Plugin Installation + +Github: https://github.com/yajra/laravel-datatables-fractal + +Run the following command in your project to get the latest version of the plugin: + +```bash +composer require yajra/laravel-datatables-fractal:"^12.0" +``` + +## Configuration +> This step is optional if you are using Laravel 5.5 + +Open the file ```config/app.php``` and then add following service provider. + +```php +'providers' => [ + // ... + Yajra\DataTables\DataTablesServiceProvider::class, + Yajra\DataTables\FractalServiceProvider::class, +], +``` + +After completing the step above, use the following command to publish configuration & assets: + +``` +php artisan vendor:publish --tag=datatables-fractal --force +``` diff --git a/html-builder-table.md b/html-builder-table.md index 4069f36..ed75ea0 100644 --- a/html-builder-table.md +++ b/html-builder-table.md @@ -8,7 +8,8 @@ Table api accepts two parameters: `$builder->table(array $attributes, $footer = ## Table Example with Footer ```php -use DataTables; +use Illuminate\Support\Facades\Route; +use Yajra\DataTables\Facades\DataTables; use Yajra\DataTables\Html\Builder; Route::get('users', function(Builder $builder) { @@ -21,7 +22,7 @@ Route::get('users', function(Builder $builder) { ['data' => 'name', 'footer' => 'Name'], ['data' => 'email', 'footer' => 'Email'], ['data' => 'created_at', 'footer' => 'Created At'], - ['data' => 'updated_at', 'footer' => 'Updated At'), + ['data' => 'updated_at', 'footer' => 'Updated At'], ]); return view('users.index', compact('html')); diff --git a/html-builder.md b/html-builder.md index f8204f0..4339798 100644 --- a/html-builder.md +++ b/html-builder.md @@ -11,6 +11,7 @@ You can use the `Builder` class by using Dependency Injection. use Yajra\DataTables\Html\Builder; Route::get('users', function(Builder $builder) { + // }); ``` @@ -37,37 +38,38 @@ Route::get('users', function(DataTables $dataTable) { ## Html Builder Example -```php -use DataTables; +```php filename=routes/web.php +use Yajra\DataTables\Facades\DataTables; use Yajra\DataTables\Html\Builder; +use Yajra\DataTables\Html\Column; +use App\Models\User; Route::get('users', function(Builder $builder) { - if (request()->ajax()) { + if (request()->ajax()) { return DataTables::of(User::query())->toJson(); } - $html = $builder->columns([ - ['data' => 'id', 'name' => 'id', 'title' => 'Id'], - ['data' => 'name', 'name' => 'name', 'title' => 'Name'], - ['data' => 'email', 'name' => 'email', 'title' => 'Email'], - ['data' => 'created_at', 'name' => 'created_at', 'title' => 'Created At'], - ['data' => 'updated_at', 'name' => 'updated_at', 'title' => 'Updated At']), - ]); + $html = $builder->columns([ + Column::make('id'), + Column::make('name'), + Column::make('email'), + Column::make('created_at'), + Column::make('updated_at'), + ]); - return view('users.index', compact('html')); + return view('users.index', compact('html')); }); ``` -On your `resources/views/users/index.blade.php`. -```php +```php filename=resources/views/users/index.blade.php @extends('app') @section('contents') - {!! $html->table() !!} + {{ $html->table() }} @endsection @push('scripts') - {!! $html->scripts() !!} + {{ $html->scripts() }} @endpush ``` diff --git a/html-installation.md b/html-installation.md index e0d0415..534ac95 100644 --- a/html-installation.md +++ b/html-installation.md @@ -2,11 +2,16 @@ ## Installation +Github: https://github.com/yajra/laravel-datatables-html + Run the following command in your project to get the latest version of the plugin: -`composer require yajra/laravel-datatables-html:^3.0` +```bash +composer require yajra/laravel-datatables-html:"^12.0" +``` ## Configuration + > This step is optional if you are using Laravel 5.5 Open the file ```config/app.php``` and then add following service provider. diff --git a/index-column.md b/index-column.md index a962ef9..0afb93a 100644 --- a/index-column.md +++ b/index-column.md @@ -16,4 +16,20 @@ Route::get('user-data', function() { ``` Using `addIndexColumn` will add another column on your response with a column name that is set on [`index_column`](/docs/{{package}}/{{version}}/general-settings#index-column) configuration. -The default index column name is `DT_RowIndex` +The default index column name is `DT_RowIndex`. + +If you want to customize the index used by the `DT_RowIndex`, you can use `setRowId('COLUMN')` to change the index number. + +```php +use DataTables; + +Route::get('user-data', function() { + $model = App\User::query(); + + return DataTables::eloquent($model) + ->setRowId('id') + ->toJson(); +}); +``` + +Be careful with this option, an index should be unique and an integer to be useful for DataTables. diff --git a/installation.md b/installation.md index 5cab060..8be648b 100644 --- a/installation.md +++ b/installation.md @@ -11,8 +11,8 @@ ### Requirements -- [Laravel 5.5+](https://github.com/laravel/framework) -- [jQuery DataTables v1.10.x](http://datatables.net/) +- [Laravel 12](https://github.com/laravel/framework) +- [DataTables 1.x|2.x](http://datatables.net/) ### Installing Laravel DataTables @@ -22,20 +22,20 @@ Laravel DataTables can be installed with [Composer](http://getcomposer.org/doc/0 Run the following command in your project to get the latest version of the package: ```bash -composer require yajra/laravel-datatables-oracle:^9.0 +composer require yajra/laravel-datatables-oracle:"^12.0" ``` -If you are using most of the DataTables plugins like Buttons & Html, you can alternatively use the all-in-one installer package. +If you use most of the DataTables plugins like Buttons & HTML, you can use the all-in-one installer package. ```bash -composer require yajra/laravel-datatables:^1.5 +composer require yajra/laravel-datatables:"^12.0" ``` ### Configuration > This step is optional if you are using Laravel 5.5+ -Open the file ```config/app.php``` and then add following service provider. +Open the file ```config/app.php``` or ```bootstrap/providers.php``` for Laravel 12 then add following service provider. ```php 'providers' => [ @@ -46,7 +46,7 @@ Open the file ```config/app.php``` and then add following service provider. After completing the step above, use the following command to publish configuration & assets: -``` +```bash php artisan vendor:publish --tag=datatables ``` diff --git a/introduction.md b/introduction.md index fc30ba1..aaa9b08 100644 --- a/introduction.md +++ b/introduction.md @@ -20,13 +20,10 @@ Official documentation of DataTables is available at [datatables.net](https://da ## Laravel DataTables -[![Join the chat at https://gitter.im/yajra/laravel-datatables](https://badges.gitter.im/yajra/laravel-datatables.svg)](https://gitter.im/yajra/laravel-datatables?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![License](https://poser.pugx.org/yajra/laravel-datatables-oracle/license)](https://packagist.org/packages/yajra/laravel-datatables-oracle) -[![Laravel 4.2|5.x](https://img.shields.io/badge/Laravel-4.2|5.x-orange.svg)](http://laravel.com) [![Latest Stable Version](https://poser.pugx.org/yajra/laravel-datatables-oracle/v/stable)](https://packagist.org/packages/yajra/laravel-datatables-oracle) -[![Build Status](https://travis-ci.org/yajra/laravel-datatables.svg?branch=master)](https://travis-ci.org/yajra/laravel-datatables) -[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/yajra/{{package}}/badges/quality-score.png?b=master)](https://scrutinizer-ci.com/g/yajra/{{package}}/?branch=master) + [![Total Downloads](https://poser.pugx.org/yajra/laravel-datatables-oracle/downloads)](https://packagist.org/packages/yajra/laravel-datatables-oracle) Laravel DataTables is a package that handles the [server-side](https://www.datatables.net/manual/server-side) works of [DataTables](http://datatables.net) using [Laravel](http://laravel.com). diff --git a/order-column.md b/order-column.md index 0b78517..6413db8 100644 --- a/order-column.md +++ b/order-column.md @@ -31,4 +31,17 @@ Route::get('user-data', function () { $query->orderBy('status', $order); }); }); +``` + +Disable ordering via orderColumn. + +```php +use DataTables; + +Route::get('user-data', function () { + $model = App\User::query(); + + return DataTables::eloquent($model) + ->orderColumn('name', false); +}); ``` \ No newline at end of file diff --git a/quick-starter.md b/quick-starter.md index 6d152b0..fe09e60 100644 --- a/quick-starter.md +++ b/quick-starter.md @@ -1,155 +1,140 @@ -# DataTables Quick Starter +# Quick Starter -## Create new project + +## 01. Installing Laravel & DataTables -``` +### Quick Installation + +If you have already installed [Laravel Installer](https://laravel.com/docs#your-first-laravel-project) on your local machine, you may create a new project via laravel command: + +```shell laravel new datatables -cd datatables -cp .env.example .env -php artisan key:generate ``` -## Setup database and ENV configuration +After the project has been created, we will then install [Laravel UI](https://github.com/laravel/ui) and [Yajra DataTables](https://github.com/yajra/laravel-datatables) + +```shell +cd datatables + +composer require laravel/ui --dev +php artisan ui bootstrap --auth -Create a new database and update `.env` file and set the datbase credentials. +composer require yajra/laravel-datatables +``` -## Install package and publish assets +For simplicity, you may use SQLite to store your application's data. To instruct Laravel to use SQLite instead of MySQL, update your new application's `.env` file and remove all of the `DB_*` environment variables except for the `DB_CONNECTION` variable, which should be set to `sqlite`: +```shell +touch database/database.sqlite ``` -composer require yajra/laravel-datatables -php artisan vendor:publish --tag=datatables-buttons +```dotenv filename=.env +DB_CONNECTION=sqlite ``` -## Setup Laravel UI + +## 02. Install Laravel DataTables Vite -``` -composer require laravel/ui --dev -php artisan ui bootstrap --auth +Next, we will install [Laravel DataTables Vite](https://github.com/yajra/laravel-datatables-vite) to simplify our frontend setup. + +```shell +npm i laravel-datatables-vite --save-dev ``` -## Install Datatables.net assets +This will install the following packages: ``` -yarn add datatables.net-bs4 datatables.net-buttons-bs4 + - Bootstrap Icons + - DataTables with Buttons and Select plugins for Bootstrap 5 + - Laravel DataTables custom scripts ``` -## Register datatables.net assets in bootstrap.js and app.scss - -Edit `resources/js/bootstrap.js` and add the following: +Once installed, we can now configure our scripts and css needed for our application. - require('bootstrap'); - require('datatables.net-bs4'); - require('datatables.net-buttons-bs4'); +```js filename=resources/js/app.js +import './bootstrap'; +import 'laravel-datatables-vite'; +``` -Edit `resources/scss/app.scss` and add the following: +```postcss filename=resources/sass/app.scss +// Fonts +@import url('https://fonts.bunny.net/css?family=Nunito'); - // DataTables - @import "~datatables.net-bs4/css/dataTables.bootstrap4.css"; - @import "~datatables.net-buttons-bs4/css/buttons.bootstrap4.css"; +// Variables +@import 'variables'; -## Compile assets +// Bootstrap +@import 'bootstrap/scss/bootstrap'; -``` -yarn dev / watch / prod +// DataTables +@import 'bootstrap-icons/font/bootstrap-icons.css'; +@import "datatables.net-bs5/css/dataTables.bootstrap5.min.css"; +@import "datatables.net-buttons-bs5/css/buttons.bootstrap5.min.css"; +@import 'datatables.net-select-bs5/css/select.bootstrap5.css'; ``` -## Create controller and DataTable class +We just need to start the Vite development server to automatically recompile our JS, CSS and refresh the browser when we make changes to our Blade templates: -``` -php artisan make:controller UsersController -php artisan datatables:make Users +```shell +npm run dev ``` -### UsersController + +## 03. Setup a Users DataTable -```php -namespace App\Http\Controllers; +Open a new terminal in your `datatables` project directory and run the following command: -use App\DataTables\UsersDataTable; - -class UsersController extends Controller -{ - public function index(UsersDataTable $dataTable) - { - return $dataTable->render('users.index'); - } -} +```shell +php artisan datatables:make Users ``` -### UsersDataTable +Next, we will configure our `UsersDataTable` and add the columns that we want to display. -```php +```php filename=app/DataTables/UsersDataTable.php namespace App\DataTables; -use App\User; +use App\Models\User; +use Illuminate\Database\Eloquent\Builder as QueryBuilder; +use Yajra\DataTables\EloquentDataTable; +use Yajra\DataTables\Html\Builder as HtmlBuilder; use Yajra\DataTables\Html\Button; use Yajra\DataTables\Html\Column; -use Yajra\DataTables\Html\Editor\Editor; -use Yajra\DataTables\Html\Editor\Fields; use Yajra\DataTables\Services\DataTable; class UsersDataTable extends DataTable { - /** - * Build DataTable class. - * - * @param mixed $query Results from query() method. - * @return \Yajra\DataTables\DataTableAbstract - */ - public function dataTable($query) + public function dataTable(QueryBuilder $query): EloquentDataTable { - return datatables() - ->eloquent($query) - ->addColumn('action', 'users.action'); + return (new EloquentDataTable($query))->setRowId('id'); } - /** - * Get query source of dataTable. - * - * @param \App\User $model - * @return \Illuminate\Database\Eloquent\Builder - */ - public function query(User $model) + public function query(User $model): QueryBuilder { return $model->newQuery(); } - /** - * Optional method if you want to use html builder. - * - * @return \Yajra\DataTables\Html\Builder - */ - public function html() + public function html(): HtmlBuilder { return $this->builder() ->setTableId('users-table') ->columns($this->getColumns()) ->minifiedAjax() - ->dom('Bfrtip') ->orderBy(1) - ->buttons( - Button::make('create'), - Button::make('export'), + ->selectStyleSingle() + ->buttons([ + Button::make('add'), + Button::make('excel'), + Button::make('csv'), + Button::make('pdf'), Button::make('print'), Button::make('reset'), - Button::make('reload') - ); + Button::make('reload'), + ]); } - /** - * Get columns. - * - * @return array - */ - protected function getColumns() + public function getColumns(): array { return [ - Column::computed('action') - ->exportable(false) - ->printable(false) - ->width(60) - ->addClass('text-center'), Column::make('id'), Column::make('name'), Column::make('email'), @@ -158,62 +143,96 @@ class UsersDataTable extends DataTable ]; } - /** - * Get filename for export. - * - * @return string - */ - protected function filename() + protected function filename(): string { - return 'Users_' . date('YmdHis'); + return 'Users_'.date('YmdHis'); } } ``` -## Update app layout - -Add scripts before the body end tag of `resources/views/layouts/app.blade.php` + +## 04. Setup a Users Controller, View & Route -``` - - - @stack('scripts') +```shell +php artisan make:controller UsersController ``` -## Create users index file +```php filename=app/Http/Controllers/UsersController.php +namespace App\Http\Controllers; -Create new file: `resources/views/users/index.blade.php`. +use App\DataTables\UsersDataTable; -```php +class UsersController extends Controller +{ + public function index(UsersDataTable $dataTable) + { + return $dataTable->render('users.index'); + } +} +``` + +```blade filename=resources/views/users/index.blade.php @extends('layouts.app') @section('content') - {{$dataTable->table()}} +
+
+
Manage Users
+
+ {{ $dataTable->table() }} +
+
+
@endsection @push('scripts') - {{$dataTable->scripts()}} + {{ $dataTable->scripts(attributes: ['type' => 'module']) }} @endpush ``` -## Register users route +```php filename=routes/web.php +use App\Http\Controllers\UsersController; -Update `routes/web.php`. +Route::get('/users', [UsersController::class, 'index'])->name('users.index'); +``` -```php -Route::get('/users', 'UsersController@index')->name('users.index'); + +## 05. Update the default app layout + +To be able to load our custom scripts, we need to add `@stack('scripts')` before the end of `body` tag in our `app.blade.php` layout. + +```blade filename=resources/views/layouts/app.blade.php +.... +
+ @yield('content') +
+ + @stack('scripts') + + ``` -## Create dummy data using tinker + +## 06. Migrate and Seed Test Data -```php +```shell +php artisan migrate php artisan tinker +``` +```php Psy Shell v0.9.9 (PHP 7.2.22 — cli) by Justin Hileman ->>> factory('App\User', 100)->create() +>>> User::factory(100)->create() +``` + +Our application should now be ready to run. + +```shell +php artisan serve ``` -## Access Users DataTables +Once you have started the Artisan development server, your application will be accessible in your web browser at [http://localhost:8000]([http://localhost:8000). -http://datatables.test/users +We can now visit our [`/users`](http://localhost:8000/users) route and see our users table. +Laravel DataTables Users diff --git a/relationships.md b/relationships.md index ab91039..cccbd46 100644 --- a/relationships.md +++ b/relationships.md @@ -47,6 +47,10 @@ Looking at `{data: 'posts', name: 'posts.title'},`: - `data: posts` represents the data key (`data.posts`) that we are going to display on our table. - `name: posts.title` represents the `User` model relationship (`posts`) and the column we are going to perform our search (`title`). +It is advised that you include select('table.') on query to avoid weird issues where id from related model replaces the id of the main model. +```php +$posts = Post::with('user')->select('posts.*'); +``` ## Nested Relationships Same strategy goes for nested relationships but do **NOTE** that ordering is not yet fully tested on nested relationships. diff --git a/response-array.md b/response-array.md index 59270ee..aa73ff1 100644 --- a/response-array.md +++ b/response-array.md @@ -1,6 +1,6 @@ # Array Response -Array response is the default response of DataTables. +The default response of the package is an array of objects. If you prefer to return an array response, use `make(false)`. ```php use DataTables; @@ -10,7 +10,7 @@ Route::get('user-data', function() { return DataTables::eloquent($model) ->addColumn('intro', 'Hi {{$name}}!') - ->make(); + ->make(false); }); ``` diff --git a/response-object.md b/response-object.md index 84b13b5..6c1c088 100644 --- a/response-object.md +++ b/response-object.md @@ -1,6 +1,6 @@ # Object Response -To convert the response of DataTables to an object, just pass `true` on `make` api. +To convert the response of DataTables to an object, use `toJson` api. ```php use DataTables; diff --git a/row-options.md b/row-options.md index 11c975e..50b0a5d 100644 --- a/row-options.md +++ b/row-options.md @@ -49,7 +49,7 @@ Setting row class via `blade` string. ## Row Data -Setting row class via `closure`. +Setting row data via `closure`. ```php ->setRowData([ @@ -62,7 +62,7 @@ Setting row class via `closure`. ]) ``` -Setting row class via `blade` string. +Setting row data via `blade` string. ```php ->setRowData([ @@ -74,7 +74,7 @@ Setting row class via `blade` string. ## Row Attributes -Setting row class via `closure`. +Setting row attribute via `closure`. ```php ->setRowAttr([ @@ -84,10 +84,10 @@ Setting row class via `closure`. ]) ``` -Setting row class via `blade` string. +Setting row attribute via `blade` string. ```php ->setRowAttr([ 'color' => '{{$color}}', ]) -``` \ No newline at end of file +``` diff --git a/search-panes-hide-columns.md b/search-panes-hide-columns.md new file mode 100644 index 0000000..9d51f67 --- /dev/null +++ b/search-panes-hide-columns.md @@ -0,0 +1,14 @@ +# Exclude Columns + +Some columns you might not want in your SearchPanes, to hide them you can add `->searchPanes(false)` in your column +definition: + +```php +protected function getColumns() : array +{ + return [ + Column::make('id') + ->searchPanes(false); + ] +} +``` \ No newline at end of file diff --git a/search-panes-options.md b/search-panes-options.md new file mode 100644 index 0000000..4026db4 --- /dev/null +++ b/search-panes-options.md @@ -0,0 +1,30 @@ +# Further SearchPanes options + +```php +public function html() : \Yajra\DataTables\Html\Builder +{ + return $this->builder() + ->searchPanes( + SearchPane::make() + ->hideCount() // Hides the count next to the options, the amount of records with the filters + ->hideTotal() // Hides the total how many are available without the filters + ->clear(false) // Hides the clear button, used to clear the user selection + ->controls(false) // disable controls (search for filters) + ->layout('columns-2') // can be used to set the layout (amount of search panes in one row) + ->order(['user_id', 'age']) // Sets the order of the search panes, uses the name of the search pane + ->orderable(false) // If the order icons should be displayed in the interface + ->panes( // Can be used to add additional search panes which do not belong to any existing column + [ + // SearchPane::make()... + ] + ) + ->dtOpts( // Sets the options for the datatables inside the searchpanes + [ + 'paging' => true, + 'pagingType' => 'numbers' + ] + ) + + ); +} +``` diff --git a/search-panes-starter.md b/search-panes-starter.md new file mode 100644 index 0000000..c363b22 --- /dev/null +++ b/search-panes-starter.md @@ -0,0 +1,116 @@ +# Getting Started + +[SearchPanes](https://datatables.net/extensions/searchpanes/) ([example](https://datatables.net/extensions/searchpanes/examples/initialisation/simple.html)) +allow the user to quickly filter the datatable after predefined filters. + +> {note} To use datatables you need to make sure that the npm packages `datatables.net-select-bs4` and `datatables.net-searchpanes-bs4` are installed and added to your `app.js`/`app.css` files. + +## Adding SearchPanes to the frontend + +To be able to see SearchPanes you need to either add them fixed in the dom (displayed at all time) or add a button which +opens them as popup. + + +### Adding SearchPanes fixed in the dom + +SearchPanes can be added to a table via the dom string, in it, they are marked with a `P` if you for example +are using `Bfrtip` as dom you can use `PBfrtip` to display the SearchPanes at the top of the datatable, or `BfrtipP` +to display them at the very bottom. + +Setting the dom String with the `\Yajra\DataTables\Html\Builder`: + +```php +public function html() : \Yajra\DataTables\Html\Builder +{ + // Setting the dom string directly + return $this->builder() + ->searchPanes(SearchPane::make()) + ->dom('PBfrtip'); + + // Alternatively set the dom with parameters + return $this->builder() + ->searchPanes(SearchPane::make()) + ->parameters([ + 'dom' => 'PBfrtip' + ]); +} +``` + + +### Adding SearchPanes with a button + +To add a button which opens the SearchPanes you need to make one extending `searchPanes`: + +```php +public function html() : \Yajra\DataTables\Html\Builder +{ + // Adding via class + return $this->builder() + ->searchPanes(SearchPane::make()) + ->buttons([ + \Yajra\DataTables\Html\Button::make('searchPanes') + // other buttons... + ]); + + // Alternatively set the buttons with options + return $this->builder() + ->searchPanes(SearchPane::make()) + ->parameters([ + 'buttons' => ['searchPanes', /*other buttons...*/] + ]); +} +``` + + +## Adding SearchPanes to the backend + +The SearchPanes can be filled in the datatables declaration via the `searchPane()` method. The method takes the column +for which the SearchPane is, as well as the options of the SearchPane. It also allows you to set custom processing for +the options. + + +```php +public function dataTable($query) : Yajra\DataTables\DataTableAbstract +{ + return datatables() + ->eloquent($query) + // Adding the SearchPane + ->searchPane( + /* + * This is the column for which this SearchPane definition is for + */ + 'user_id', + + /* + * Here we define the options for our SearchPane. This should be either a collection or an array with the + * form: + * [ + * [ + * 'value' => 1, + * 'label' => 'display value', + * 'total' => 5, // optional + * 'count' => 3 // optional + * ], + * [ + * 'value' => 2, + * 'label' => 'display value 2', + * 'total' => 6, // optional + * 'count' => 5 // optional + * ], + * ] + */ + fn() => User::query()->select('id as value', 'name as label')->get(), + + /* + * This is the filter that gets executed when the user selects one or more values on the SearchPane. The + * values are always given in an array even if just one is selected + */ + function (\Illuminate\Database\Eloquent\Builder $query, array $values) { + return $query + ->whereIn( + 'id', + $values); + } + ); +} +``` diff --git a/skip-total-records.md b/skip-total-records.md index aa00a6b..0400387 100644 --- a/skip-total-records.md +++ b/skip-total-records.md @@ -1,5 +1,7 @@ # Skip Total Records +> Note: This is deprecated on v10. Just use setTotalRecords instead. + Skip total records aims to improve dataTables response time by skipping the total records count query and settings its value equals to the filtered total records.