Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

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

Provide feedback

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

Saved searches

Use saved searches to filter your results more quickly

Sign up

Generate tables from Eloquent models.

License

NotificationsYou must be signed in to change notification settings

Okipa/laravel-table

Repository files navigation

I've been quite busy professionally lately and I'm currently looking for one or more co-maintainers to help me to maintain and develop this package.

Current roadmap:

  • PR reviewing
  • Livewire 3 compatibility
  • Tailwind 3 compatibility

Please contact me at arthur[dot]lorent[at]gmail.com to apply.


Laravel Table

Latest Stable VersionTotal DownloadsBuild StatusCoverage StatusLicense: MIT

Generate tables from Eloquent models

Save time and easily render tables in your views from Eloquent models.

Tables can be generated under the following UI frameworks:

  • Bootstrap 5
  • Bootstrap 4
  • TailwindCSS 3 (upcoming feature)

Found this package helpful? Please consider supporting my work!

DonateDonate

Compatibility

Laravel versionLivewire versionPHP versionPackage version
^9.0 | ^10.0^2.08.1.* | 8.2.*^5.3
^8.0 | ^9.0^2.0^8.1^5.0
^7.0 | ^8.0X^7.4 | ^8.0^4.0
^7.0 | ^8.0X^7.4 | ^8.0^3.0
^6.0 | ^7.0X^7.4 | ^8.0^2.0
^5.8 | ^6.0 | ^7.0X^7.2 | ^7.3 | ^7.4^1.3
^5.5 | ^5.6 | ^5.7 | ^5.8 | ^6.0X^5.8 | ^7.1^1.0

Upgrade guide

Usage

Create your table with the following command:

php artisan make:table UsersTable --model=App/Models/User

Configure your table in theUsersTable generated class, which can be found in theapp\Tables directory:

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Column;useOkipe\LaravelTable\Formatters\Date;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [            Column::make('id')->sortable(),            Column::make('name')->searchable()->sortable(),            Column::make('email')->searchable()->sortable(),            Column::make('created_at')                ->format(newDateFormatter('d/m/Y H:i','Europe/Paris'))                ->sortable(),            Column::make('updated_at')                ->format(newDateFormatter('d/m/Y H:i','Europe/Paris'))                ->sortable()                ->sortByDefault('desc'),        ];    }}

And display it in a view:

<livewire:table:config="App\Tables\UsersTable::class"/>

Table of contents

Installation

  • Install the package with composer:
composer require okipa/laravel-table

This package usesLivewire under the hood and its installation is required.

You'll have to follow theinstallation instructions if Livewire is not already installed on your project.

Configuration

Optionally publish the package configuration:

php artisan vendor:publish --tag=laravel-table:config

Templates

Optionally publish the package templates:

php artisan vendor:publish --tag=laravel-table:views

Translations

All words and sentences used in this package are translatable.

See how to translate them on the Laravel official documentation:https://laravel.com/docs/localization#using-translation-strings-as-keys.

Here is the list of the words and sentences available for translation:

Status

  • Loading in progress...
  • No results were found.
  • You can rearrange the order of the items in this list using a drag and drop action.
  • Reset filters
  • Yes
  • No
  • Search by:
  • Reset research
  • Number of rows per page
  • Sort ascending
  • Sort descending
  • Actions
  • Bulk Actions
  • Create
  • Add
  • Show
  • Edit
  • Destroy
  • Activate
  • Deactivate
  • Verify Email
  • Unverify Email
  • Toggle On
  • Toggle Off
  • Are you sure you want to execute the action :action on the line #:primary?
  • Are you sure you want to execute the action :action on the field :attribute from the line #:primary?
  • Are you sure you want to execute the action :action on the :count selected lines?
  • The line #:primary does not allow the action :action and will not be affected.
  • :count selected lines do not allow the action :action and will not be affected.
  • The action :action has been executed on the line #:primary.
  • The action :action has been executed on the field :attribute from the line #:primary.
  • The action :action has been executed on the :count selected lines.
  • The line #:primary does not allow the action :action and was not affected.
  • :count selected lines do not allow the action :action and were not affected.
  • The list has been reordered.
  • Showing results <b>:start</b> to <b>:stop</b> on <b>:total</b>

How to

Create table configurations

Generate a table configuration by executing this command :php artisan make:table UsersTable.

If you want to generate a configuration with a predefined model, just add this option at the end:--model=App/Models/User.

You'll find all your generated table configurations in theapp/Tables directory.

Display tables in views

Just call this Livewire component in your view with your configuration class name passed in theconfig parameter.

<livewire:table:config="App\Tables\UsersTable::class"/>

Pass external data to your tables

In case you have specific attributes to transmit to your table configuration, you should pass them to theconfigParams parameter.

This could be useful when you have to transmit external information to your table.

<livewire:table:config="App\Tables\UsersTable::class":configParams="['categoryId' => 1]"/>

You should then declare the passed attributes aspublic attributes your table configuration.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{// You will now be able to use the provided `$this->categoryId` category ID in your table configuration.publicint$categoryId;// ...}

Generate tables from Eloquent models

To generate a table from an Eloquent model, you'll just have to call themodel method on your table.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }}

Override native selects behaviour on your tables

You may want to override native HTML select components behaviour on your tables.

You will be able to add a data attribute (which is known as the best practice to add extra features to a HTML component) to all the HTML select components displayed on your tables by defining an array of HTML attribute as value for thelaravel-table.html_select_components_attributes config key.

// `data-selector` HTML attribute will be appended to all tables HTML select components.'html_select_components_attributes' => ['data-selector' =>true],

Add query instructions on tables

To add specific query instructions on tables, use the availablequery method.

You'll be able to set specific Eloquent instructions by passing a closure parameter to thequery method on your table.

This closure will allow you to manipulate a\Illuminate\Database\Eloquent\Builder $query argument.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useIlluminate\Database\Eloquent\Builder;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->query(fn(Builder$query) =>$query->where('category_id',1));    }   }

Handle tables number of rows per page, pagination and navigation status

You have two ways to allow or disallow users to choose the number of rows that will be displayed per page:

  • Activate or deactivate it globally from thelaravel-table.enable_number_of_rows_per_page_choice config boolean value
  • Override global activation status by executing theenableNumberOfRowsPerPageChoice() method on your table
namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->enableNumberOfRowsPerPageChoice(false);    }}

Following the same logic, you'll be able to define the number of rows per page options that will be available for selection:

  • Set options globally from thelaravel-table.number_of_rows_per_page_default_options config array value
  • Override global options by executing thenumberOfRowsPerPageOptions() method on your table

The first available option will be automatically selected and applied on table initialization.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)// Table will display 5 rows on initialization and will allow displaying 10, 15, 20 or 25 rows.            ->numberOfRowsPerPageOptions([5,10,15,20,25]);    }}

Pagination will automatically be handled, according to the number of rows to display and the total number of rows, as well as a navigation status.

Both of them will be displayed in the table footer.

Set conditional row class

Define conditional row class on tables by passing a closure argument to therowClass method.

This closure will allow you to manipulate aIlluminate\Database\Eloquent $model argument and has to return an array of classes where the array key contains the class or classes you wish to add, while the value is a boolean expression.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->rowClass(fn(User$user) => ['table-danger' => !$user->active,            ]);    }}

Setup table filters

Configuring table filters will make them appear asselect HTML components on a dedicated bar above the table.

The filters bar will not appear if no filter is declared.

This package provides the following built-in filters:

  • ValueFilter:
    • Requiresstring $label,string $attribute,array $options andbool $multiple = true arguments on instantiation
    • Filters the table based on whether the value of the selected options (or single option if multiple mode is disabled) is found in the given attribute
  • RelationshipFilter:
    • Requiresstring $label,string $relationship,array $options andbool $multiple = true arguments on instantiation
    • Filters the table based on whether the value of the selected options (or single option if multiple mode is disabled) is found in the given relationship
  • NullFilter
    • Requires astring $attribute argument on instantiation
    • Filters the table based on whether the value of the given attribute isnull or not
  • BooleanFilter
    • Requiresstring $label andstring $attribute arguments on instantiation
    • Filters the table based on whether the value of the given attribute istrue orfalse

To use them, you'll have to pass an array to thefilters method, containing the filter instances to declare.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Filters\NullFilter;useOkipa\LaravelTable\Filters\ValueFilter;useOkipa\LaravelTable\Filters\BooleanFilter;useOkipa\LaravelTable\Filters\RelationshipFilter;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->filters([newValueFilter('Email','email', User::pluck('email','email')->toArray()),newRelationshipFilter('Categories','categories', UserCategory::pluck('name','id')->toArray()),newNullFilter('Email Verified','email_verified_at'),newBooleanFilter('Active','active'),            ]);    }}

You may need to create your own filters. To do so, execute the following command:php artisan make:table:filter MyNewFilter.

You'll find your generated table filter in theapp/Tables/Filters directory.

You will now be able to use your new filter in your tables.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useApp\Tables\Filters\MyNewFilter;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->filters([newMyNewFilter(),            ]);    }}

Define table head action

Configure a table action that will be displayed as a button positioned at the right of the table head.

If no head action is declared, the dedicated slot for it in the table head will remain empty.

This package provides the following built-in head actions:

  • RedirectHeadAction:
    • Requiresstring $url,string $label,string $icon,array $class = ['btn', 'btn-success'] andbool $openInNewWindow = false arguments on instantiation
    • Redirects to the given URL from a click on the button
  • CreateHeadAction:
    • Requiresstring $createUrl andbool $openInNewWindow = false arguments on instantiation
    • Instantiate a pre-configuredRedirectHeadAction with$createUrl as URL,__('Create') as label andconfig('laravel-table.icon.create') as icon

To use one of them, you'll have to pass an instance of it to theheadAction method.

You'll be able to chain the following method to your head action:

  • when(bool $condition): Okipa\LaravelTable\Abstracts\AbstractHeadAction
    • Determines whether the head action should be enabled
namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\HeadActions\AddHeadAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)// Create head action will not be available when authenticated user is not allowed to create users            ->headAction((newAddHeadAction(route('user.create')))->when(Auth::user()->cannot('create_users')));    }}

You may need to create your own head actions. To do so, execute the following command:php artisan make:table:head:action MyNewHeadAction.

You'll find your generated table head action in theapp/Tables/HeadActions directory.

You will now be able to use your new head action in your tables.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useApp\Tables\HeadActions\MyNewHeadAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->headAction(newMyNewHeadAction());    }}

Define table bulk actions

Configure table bulk actions that will be available in a dropdown positioned at the left of the table head.

If no bulk action is declared on your table, the dedicated column will not be displayed.

Important note:you'll have to set up a few lines of javascript to allow bulk actions confirmation requests and feedback to be working properly.

This package provides the built-in following bulk actions:

  • VerifyEmailBulkAction:
    • Requires astring $attribute argument on instantiation
    • Update the given attribute with the current datetime for all selected lines
  • CancelEmailVerificationBulkAction:
    • Requires astring $attribute argument on instantiation
    • Update the given attribute tonull for all selected lines
  • ActivateBulkAction:
    • Requires astring $attribute argument on instantiation
    • Update the given attribute totrue for all selected lines
  • DeactivateBulkAction:
    • Requires astring $attribute argument on instantiation
    • Update the given attribute tofalse for all selected lines
  • DestroyBulkAction:
    • Destroys all the selected lines

To use them, you'll have to pass a closure parameter to thebulkActions method. This closure will allow you to manipulate aIlluminate\Database\Eloquent $model argument and has to return an array containing bulk action instances.

You'll be able to chain the following methods to your bulk actions:

  • when(bool $condition): Okipa\LaravelTable\Abstracts\AbstractBulkAction
    • Determines whether the bulk action should be enabled on the table rows
  • confirmationQuestion(string|false $confirmationQuestion): Okipa\LaravelTable\Abstracts\AbstractBulkAction
    • Overrides the default action confirmation message
  • feedbackMessage(string|false $feedbackMessage): Okipa\LaravelTable\Abstracts\AbstractBulkAction:
    • Overrides the default action feedback message
namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\BulkActions\DestroyBulkAction;useOkipa\LaravelTable\BulkActions\ActivateBulkAction;useOkipa\LaravelTable\BulkActions\DeactivateBulkAction;useOkipa\LaravelTable\BulkActions\VerifyEmailBulkAction;useOkipa\LaravelTable\BulkActions\CancelEmailVerificationBulkAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->bulkActions(fn(User$user) => [newVerifyEmailBulkAction('email_verified_at'),newCancelEmailVerificationBulkAction('email_verified_at'),newActivateBulkAction('active'),newDeactivateBulkAction('active'),                (newDestroyBulkAction())// Destroy action will not be available for authenticated user                    ->when(Auth::user()->isNot($user))// Override the action default confirmation question// Or set `false` if you do not want to require any confirmation for this action                    ->confirmationQuestion('Are you sure you want to delete selected users ?')// Override the action default feedback message// Or set `false` if you do not want to trigger any feedback message for this action                    ->feedbackMessage('Selected users have been deleted.'),            ]);    }}

You may need to create your own bulk actions. To do so, execute the following command:php artisan make:table:bulk:action MyNewBulkAction.

You'll find your generated table bulk actions in theapp/Tables/BulkActions directory.

You will now be able to use your new bulk action in your tables.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useApp\Tables\BulkActions\MyNewBulkAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->bulkActions(fn(User$user) => [newMyNewBulkAction(),            ]);    }}

Define table row actions

Configure row actions on your table that will be displayed at the end of each row.

If no row action is declared on your table, the dedicatedActions column at the right of the table will not be displayed.

Important note:you'll have to set up a few lines of javascript to allow row actions confirmation requests and feedback to be working properly.

This package provides the built-in following row actions:

  • RedirectRowAction:
    • Requiresstring $url,string $title,string $icon,array $class = ['link-info'],string|null $defaultConfirmationQuestion = null,string|null $defaultFeedbackMessage = null andbool $openInNewWindow = false arguments on instantiation
    • Redirects to the given URL from a click on the link
  • ShowRowAction:
    • Requiresstring $showUrl andbool $openInNewWindow = false arguments on instantiation
    • Instantiate a pre-configuredRedirectRowAction with$showUrl as URL,__('Show') as label andconfig('laravel-table.icon.show') as icon
  • EditRowAction:
    • Requires astring $editUrl argument on instantiation
    • Redirects to the model edit page on click
  • DestroyRowAction:
    • Destroys the line after being asked to confirm

To use them, you'll have to pass a closure parameter to therowActions method. This closure will allow you to manipulate aIlluminate\Database\Eloquent $model argument and has to return an array containing row action instances.

You'll be able to chain the same methods as for a bulk action =>See bulk actions configuration.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\RowActions\EditRowAction;useOkipa\LaravelTable\RowActions\ShowRowAction;useOkipa\LaravelTable\RowActions\DestroyRowAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->rowActions(fn(User$user) => [newShowRowAction(route('user.show',$user)),newEditRowAction(route('user.edit',$user)),                (newDestroyRowAction())// Destroy action will not be available for authenticated user                    ->when(Auth::user()->isNot($user))// Override the action default confirmation question// Or set `false` if you do not want to require any confirmation for this action                    ->confirmationQuestion('Are you sure you want to delete user' .$user->name .'?')// Override the action default feedback message// Or set `false` if you do not want to trigger any feedback message for this action                    ->feedbackMessage('User' .$user->name .' has been deleted.'),            ]);    }}

You may need to create your own row actions. To do so, execute the following command:php artisan make:table:row:action MyNewRowAction.

You'll find your generated table row actions in theapp/Tables/RowActions directory.

You will now be able to use your new row action in your tables.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useApp\Tables\RowActions\MyNewRowAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)            ->rowActions(fn(User$user) => [newMyNewRowAction(),            ]);    }}

You may need your row actions to be confirmed before they'll be executed and to trigger feedback messages.

You'll have to configure them in the same way you did forbulk actions.

Declare columns on tables

Declare columns on tables with thecolumns method available in your generated table configuration, from which you'll have to return an array of column instances.

To declare columns, just use the staticmake method that will await astring $attribute argument. This attribute will be used to get the default cell value.

By default, the column title will be defined to__('validation.attributes.<attribute>') in order to reuse attributes translations.

If you need to, you may use thetitle method that will await astring $title argument to set a specific column title that will override the default one.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Column;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Column attribute set to `id`, column value set from `$user->id` and colum title set to `__('validation.attributes.id')`            Column::make('id'),// Column attribute set to `name`, value set from `$user->name` and column title set to `Username`            Column::make('name')->title('Username'),        ];    }}

Format column values

You'll sometimes need to apply specific formatting for your columns. There are a few ways to achieve this.

For specific cases, you should pass a closure parameter to theformat method on your column.

This closure will allow you to manipulate aIlluminate\Database\Eloquent $model argument.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Column;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Value set from `$user->id`            Column::make('id'),// Value set from closure            Column::make('username')                ->format(fn(User$user) =>'<b>' .$user->companies->implode('name',',') .'</b>'),        ];    }}

If you want to apply the same formatting treatment repeatedly, you should create a formatter with the following command:php artisan make:table:formatter NewFormatter.

You'll find the generated formatter in theapp\Table\Formatters directory.

You'll be able to reuse this formatter in your tables.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Column;useApp\Tables\Formatters\NewFormatter;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [            Column::make('id'),            Column::make('name')->format(newNewFormatter()),        ];    }}

This package provides the following built-in formatters :

  • BooleanFormatter:
    • Displays theconfig('laravel-table.icon.active') active icon or theconfig('laravel-table.icon.inactive') inactive icon from aboolean value
  • DateFormatter:
    • Requiresstring $format andstring $timezone arguments on instantiation
    • Displays a formatted string from adate ordatetime value
  • StrLimitFormatter:
    • Allows optionalint $limit andstring $end arguments on instantiation
    • Displays a truncated string with a title allowing to see the full string on hover

Define column actions

Configure column actions on your table that will be displayed on their own cells.

Column actions have a lot in common with row actions.

Important note:you'll have to set up a few lines of javascript to allow column actions confirmation requests and feedback to be working properly.

This package provides the built-in following actions:

  • ToggleBooleanColumnAction:
    • Toggles the email verification status
  • ToggleBooleanColumnAction:
    • Toggles a boolean value

To use them, you'll have to pass a closure parameter to theaction method. This closure will allow you to manipulate aIlluminate\Database\Eloquent $model argument and has to return anAbstractColumnAction instance.

You'll be able to chain the same methods as for a bulk action =>See bulk actions configuration.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\ColumnActions\ToggleBooleanColumnAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;useOkipa\LaravelTable\ColumnActions\ToggleBooleanColumnAction;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [            Column::make('id'),            Column::make('email_verified_at')// ToggleBooleanColumnAction action will not trigger any feedback message                ->action(fn(User$user) => (newToggleBooleanColumnAction()->feedbackMessage(false))            Column::make('active')// ToggleBooleanColumnAction action will not be available for authenticated user                ->action(fn(User$user) => (newToggleBooleanColumnAction())->when(Auth::user()->isNot($user))),        ];    }}

You may need to create your own column actions. To do so, execute the following command:php artisan make:table:column:action MyNewColumnAction.

You'll find your generated table column actions in theapp/Tables/ColumnActions directory.

You will now be able to use your new column action in your tables.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useApp\Tables\ColumnActions\MyNewColumnAction;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [            Column::make('id'),            Column::make('action')->action(fn() =>newMyNewColumnAction()),        ];    }}

You may need your column actions to be confirmed before they'll be executed and to trigger feedback messages.

You'll have to configure them in the same way you did forbulk actions.

Configure columns searching

Allow searching on columns by calling thesearching method.

When searchable fields are set, a search input will appear in the table head.

Searchable column titles will be used to indicate which field can be searched on the search input placeholder.

By default, searching will be applied to columns defined keys.

class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Column will not be searchable            Column::make('id'),// Table will be searchable from `$user->name`            Column::make('name')->searchable(),        ];    }}

You will be able to set up a custom searching behaviour by passing a closure to thesearchable method.

This closure will be executed when searching will be triggered on the table and will allow you to manipulate aIlluminate\Database\Eloquent\Builder $query argument.

class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Column will not be searchable            Column::make('id'),// Column will be searchable using this closure            Column::make('owned_companies')// ... Your custom formatting here                ->searchable(fn(Builder$query,string$searchBy) =>$query->whereRelation('companies','name','LIKE','%' .$searchBy .'%'                ),        ];    }}

Configure columns sorting

Allow sorting on columns by calling thesortable method.

Sortable columns will display clickable sort icons before their titles that will trigger ascending or descending sorting.

By default, sorting will be applied to columns defined keys.

class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Column will not be sortable            Column::make('id'),// Column will be sortable from `$user->name`            Column::make('name')->sortable(),        ];    }}

To sort a column by default, use thesortByDefault column method, which will allow you to pass astring $direction argument.

You can sort by default a column that is not sortable.

class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Column will not be sortable            Column::make('id'),// Column will be sorted descending by default on `$user->name`            Column::make('name')->sortByDefault('desc'),        ];    }}

You will be able to set up a custom sorting behaviour by passing a closure to thesortable method.

This closure will be executed when sorting will be triggered on the column and will allow you to manipulate aIlluminate\Database\Eloquent\Builder $query and astring $sortDir arguments (asc ordesc).

class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [// Column will not be sortable            Column::make('id'),// Column will be sortable from this closure            Column::make('companies_count')// Custom formatting...                ->sortable(fn(Builder$query,string$sortDir) =>$query                    ->withCount('companies')                    ->orderBy('companies_count',$sortDir)),        ];    }}

Allow columns to be reordered from drag and drop action

Allow columns to be reordered from drag and drop action by calling thereorderable method on your table.

This method will await a firststring $attribute argument, an optional secondstring $title argument, and an optional thirdstring $sortDirByDefault argument (acceptingasc ordesc values).

Important notes:

Activating this feature will:

  • Prepend a new column that will display the drag-and-drop icon defined in thelaravel-table.icon.drag_drop config value, followed by the defined model order attribute value
  • Sort the rows from the defined model order attribute (asc by default)
  • Disable all other columns sorting as it is not compatible with drag-and-drop reordering
  • And of course, enable the drag-and-drop columns reordering by adding all theLivewire Sortable Plugin necessary markup
namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)// A new column will display the drag-and-drop icon, followed by the `position` attribute value// Rows will be sorted from the `position` model attribute and all other columns sorting will be disable            ->reorderable('position');    }}

Tip: if you are using packages likespatie/eloquent-sortable to handle your Eloquent models sorting behaviour with agrouping query, you'll have to also set this grouping query in thetable query instruction.

Declare results on tables

To display results, you'll have to return an array of result instances from theresults method available in your generated table configuration.

If no result is declared, their dedicated space will remain empty.

Results should be declared this way:

  1. Create aResult instance with the staticmake method
  2. Chain thetitle method that will await astring $title argument
  3. Chain theformat method that will await a closure, letting you manipulateIlluminate\Database\Query\Builder $totalRowsQuery andIlluminate\Support\Collection $displayedRowsCollection params
namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useOkipa\LaravelTable\Column;useOkipa\LaravelTable\Result;useIlluminate\Support\Collection;useIlluminate\Database\Query\Builder;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()->model(User::class);    }protectedfunctioncolumns():array    {return [            Column::make('id'),        ];    }protectedfunctionresults():array    {return [// This result uses the first $totalRowsQuery closure param to compute its value.// In this example, all users contained in database with unverified email will be count.            Result::make()                ->title('Total of users with unverified email')                ->format(staticfn(Builder$totalRowsQuery) =>$totalRowsQuery                    ->whereNull('email_verified_at')                    ->count()),// This result uses the second $displayedRowsCollection closure param to compute its value.// In this example, all displayed inactive users will be count.            Result::make()                ->title('Displayed inactive users')                ->format(staticfn(Builder$totalRowsQuery,Collection$displayedRowsCollection                ) =>$displayedRowsCollection->where('active',false)->count()),        ];    }}

Set up a few lines of JavaScript

You'll have to add few Javascript lines to your project once this package is installed, in order to allow confirmation requests and actions feedback to be working properly.

When an action is requesting the user confirmation, it will not be directly executed. Atable:action:confirm Livewire event will be emitted instead with the following parameters:

  1. The action type
  2. The action identifier
  3. The model primary key related to your action
  4. The$confirmationQuestion attribute from your action

As you will see on the provided snippet below, the 4th param of this event is the only one you'll have to use in order to request the user confirmation. The 3 first params are only there to be sent back to a new event when the action is confirmed by the user. Just ignore them in your treatment.

You will have to intercept this event from your own JS script and prompt a confirmation request.

When the action is confirmed by the user, you'll have to emit a newlaraveltable:action:confirmed Livewire event that will trigger the action execution. You'll have to pass it the 3 first arguments provided in thetable:action:confirm event:

  1. The action type
  2. The action identifier
  3. The model primary key related to your action

Here is an JS snippet to show you how to proceed:

// Listen to the action confirmation requestLivewire.on('laraveltable:action:confirm',(actionType,actionIdentifier,modelPrimary,confirmationQuestion)=>{// You can replace this native JS confirm dialog by your favorite modal/alert/toast library implementation. Or keep it this way!if(window.confirm(confirmationQuestion)){// As explained above, just send back the 3 first argument from the `table:action:confirm` event when the action is confirmedLivewire.emit('laraveltable:action:confirmed',actionType,actionIdentifier,modelPrimary);}});

Once an action is executed, atable:action:feedback Livewire event is triggered (it sometimes depends on the configuration of a feedback message).

Following the same logic, you'll have to intercept it from a JS script as shown on the snippet below to provide an immediate feedback to the user:

Livewire.on('laraveltable:action:feedback',(feedbackMessage)=>{// Replace this native JS alert by your favorite modal/alert/toast library implementation. Or keep it this way!window.alert(feedbackMessage);});

Finally, in order to allow headRedirectHeadAction andCreateHeadAction to open link in new tab, you'll also have to add the following JS snippet:

Livewire.on('laraveltable:link:open:newtab',(url)=>{window.open(url,'_blank').focus();});

Trigger Livewire events on table load

You may want to trigger some events on table load, in order to load UI third party JS libraries for example.

You can do it using the tableemitEventsOnLoad method, that will await an array of events.

namespaceApp\Tables;useApp\Models\User;useOkipa\LaravelTable\Table;useIlluminate\Database\Eloquent\Builder;useOkipa\LaravelTable\Abstracts\AbstractTableConfiguration;class UsersTableextends AbstractTableConfiguration{protectedfunctiontable():Table    {return Table::make()            ->model(User::class)// This event will be loaded each time your table will be rendered// in order to keep your UI third party libraries rendering,// even when its HTML is refreshed.            ->emitEventsOnLoad(['js:selector:init' => ['some','params']]);    }   }

Interact with your tables from events

You will be able to interact with your tables by sending them the following Livewire events:

  • laraveltable:refresh
    • Allows optionalarray $configParams = [], andarray $targetedConfigs = [] arguments
    • Refreshes your tables and (optionaly) setexternal table config data with (optional) table targeting to only refresh specific ones (empty$targetedConfigs array will refresh all tables one page)

Testing

composertest

Changelog

Please seeCHANGELOG for more information on what has changed recently.

Contributing

Please seeCONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please seeLicense File for more information.


[8]ページ先頭

©2009-2025 Movatter.jp