Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

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

Provide feedback

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

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jun 27, 2024. It is now read-only.

protonemedia/inertiajs-tables-laravel-query-builder

Repository files navigation

Latest Version on NPMnpmLatest Version on PackagistSoftware Licenserun-tests


This package is not maintained anymore, but it has a successor:Inertia Table 🚀

Inertia Table is a brand new, premium package that's built from the ground up. It combines the best of this package with all the enhancements and new features of the Splade variant. The package in this repository is considered legacy and won't be updated anymore. It has some architectural flaws that are fixed in the new one.

The new package has a modern foundation and many requested features likedate filters,bulk actions,exports,dark mode,built-in query builder, andbetter customization. There's also a React version coming. Check out all the features of the new package in the documentation:https://inertiaui.com/inertia-table/docs/introduction


This package provides aDataTables-like experience forInertia.js with support for searching, filtering, sorting, toggling columns, and pagination. It generates URLs that can be consumed by Spatie's excellentLaravel Query Builder package, with no additional logic needed. The components are styled withTailwind CSS 3.0, but it's fully customizable with slots. The data refresh logic is based on Inertia'sPing CRM demo.

Inertia.js Table for Laravel Query Builder

Support this package!

❤️ We proudly support the community by developing Laravel packages and giving them away for free. If this package saves you time or if you're relying on it professionally, please considersponsoring the maintenance and development. Keeping track of issues and pull requests takes time, but we're happy to help!

Features

  • Auto-fill: auto generatesthead andtbody with support for custom cells
  • Global Search
  • Search per field
  • Select filters
  • Toggle columns
  • Sort columns
  • Pagination (support for Eloquent/API Resource/Simple/Cursor)
  • Automatically updates the query string (by usingInertia's replace feature)

Compatibility

Note: There is currently anissue with using this package with Vite!

Installation

You need to install both the server-side package and the client-side package. Note that this package is only compatible with Laravel 9, Vue 3.0, and requires the Tailwind Forms plugin.

Server-side installation (Laravel)

You can install the package via composer:

composer require protonemedia/inertiajs-tables-laravel-query-builder

The package will automatically register the Service Provider which provides atable method you can use on an Interia Response.

Search fields

With thesearchInput method, you can specify which attributes are searchable. Search queries are passed to the URL query as afilter. This integrates seamlessly with thefiltering feature of the Laravel Query Builder package.

Though it's enough to pass in the column key, you may specify a custom label and default value.

useProtoneMedia\LaravelQueryBuilderInertiaJs\InertiaTable;Inertia::render('Page/Index')->table(function (InertiaTable$table) {$table->searchInput('name');$table->searchInput(        key:'framework',        label:'Find your framework',        defaultValue:'Laravel'    );});

Select Filters

Select Filters are similar to search fields but use aselect element instead of aninput element. This way, you can present the user a predefined set of options. Under the hood, this uses the same filtering feature of the Laravel Query Builder package.

TheselectFilter method requires two arguments: the key, and a key-value array with the options.

Inertia::render('Page/Index')->table(function (InertiaTable$table) {$table->selectFilter('language_code', ['en' =>'Engels','nl' =>'Nederlands',    ]);});

TheselectFilter will, by default, add ano filter option to the array. You may disable this or specify a custom label for it.

Inertia::render('Page/Index')->table(function (InertiaTable$table) {$table->selectFilter(        key:'language_code',        options:$languages,        label:'Language',        defaultValue:'nl',        noFilterOption:true,        noFilterOptionLabel:'All languages'    );});

Columns

With thecolumn method, you can specify which columns you want to be toggleable, sortable, and searchable. You must pass in at least a key or label for each column.

Inertia::render('Page/Index')->table(function (InertiaTable$table) {$table->column('name','User Name');$table->column(        key:'name',        label:'User Name',        canBeHidden:true,        hidden:false,        sortable:true,        searchable:true    );});

Thesearchable option is a shortcut to thesearchInput method. The example below will essentially call$table->searchInput('name', 'User Name').

Global Search

You may enable Global Search with thewithGlobalSearch method, and optionally specify a placeholder.

Inertia::render('Page/Index')->table(function (InertiaTable$table) {$table->withGlobalSearch();$table->withGlobalSearch('Search through the data...');});

If you want to enable Global Search for every table by default, you may use the staticdefaultGlobalSearch method, for example, in theAppServiceProvider class:

InertiaTable::defaultGlobalSearch();InertiaTable::defaultGlobalSearch('Default custom placeholder');InertiaTable::defaultGlobalSearch(false);// disable

Example controller

<?phpnamespaceApp\Http\Controllers;useApp\Models\User;useIlluminate\Support\Collection;useInertia\Inertia;useProtoneMedia\LaravelQueryBuilderInertiaJs\InertiaTable;useSpatie\QueryBuilder\AllowedFilter;useSpatie\QueryBuilder\QueryBuilder;class UserIndexController{publicfunction__invoke()    {$globalSearch = AllowedFilter::callback('global',function ($query,$value) {$query->where(function ($query)use ($value) {                Collection::wrap($value)->each(function ($value)use ($query) {$query                        ->orWhere('name','LIKE',"%{$value}%")                        ->orWhere('email','LIKE',"%{$value}%");                });            });        });$users = QueryBuilder::for(User::class)            ->defaultSort('name')            ->allowedSorts(['name','email','language_code'])            ->allowedFilters(['name','email','language_code',$globalSearch])            ->paginate()            ->withQueryString();return Inertia::render('Users/Index', ['users' =>$users,        ])->table(function (InertiaTable$table) {$table              ->withGlobalSearch()              ->defaultSort('name')              ->column(key:'name', searchable:true, sortable:true, canBeHidden:false)              ->column(key:'email', searchable:true, sortable:true)              ->column(key:'language_code', label:'Language')              ->column(label:'Actions')              ->selectFilter(key:'language_code', label:'Language', options: ['en' =>'English','nl' =>'Dutch',              ]);    }}

Client-side installation (Inertia)

You can install the package via eithernpm oryarn:

npm install @protonemedia/inertiajs-tables-laravel-query-builder --saveyarn add @protonemedia/inertiajs-tables-laravel-query-builder

Add the repository path to thecontent array of yourTailwind configuration file. This ensures that the styling also works on production builds.

module.exports={content:['./node_modules/@protonemedia/inertiajs-tables-laravel-query-builder/**/*.{js,vue}',]}

Table component

To use theTable component and all its related features, you must import theTable component and pass theusers data to the component.

<script setup>import {Table }from"@protonemedia/inertiajs-tables-laravel-query-builder";defineProps(["users"])</script><template>  <Table:resource="users" /></template>

Theresource property automatically detects the data and additional pagination meta data. You may also pass this manually to the component with thedata andmeta properties:

<template>  <Table:data="users.data":meta="users.meta" /></template>

If you want to manually render the table, like in v1 of this package, you may use thehead andbody slot. Additionally, you can still use themeta property to render the paginator.

<template>  <Table:meta="users">    <template #head>      <tr>        <th>User</th>      </tr>    </template>    <template #body>      <trv-for="(user, key) in users.data":key="key"      >        <td>{{ user.name }}</td>      </tr>    </template>  </Table></template>

TheTable has some additional properties to tweak its front-end behaviour.

<template>  <Table:striped="true":prevent-overlapping-requests="false":input-debounce-ms="1000":preserve-scroll="true"  /></template>
PropertyDescriptionDefault
stripedAdds astriped layout to the table.false
preventOverlappingRequestsCancels a previous visit on new user input to prevent an inconsistent state.true
inputDebounceMsNumber of ms to wait before refreshing the table on user input.350
preserveScrollConfigures theScroll preservation behavior. You may also passtable-top to this property to scroll to the top of the table on new data.false

Custom column cells

When usingauto-fill, you may want to transform the presented data for a specific column while leaving the other columns untouched. For this, you may use a cell template. This example is taken from theExample Controller above.

<template>  <Table:resource="users">    <template #cell(actions)="{ item: user }">      <a:href="`/users/${user.id}/edit`">        Edit      </a>    </template>  </Table></template>

Multiple tables per page

You may want to use more than one table component per page. Displaying the data is easy, but using features like filtering, sorting, and pagination requires a slightly different setup. For example, by default, thepage query key is used for paginating the data set, but now you want two different keys for each table. Luckily, this package takes care of that and even provides a helper method to support Spatie's query package. To get this to work, you need toname your tables.

Let's take a look at Spatie'sQueryBuilder. In this example, there's a table for the companies and a table for the users. We name the tables accordingly. So first, call the staticupdateQueryBuilderParameters method to tell the package to use a different set of query parameters. Now,filter becomescompanies_filter,column becomescompanies_column, and so forth. Secondly, change thepageName of the database paginator.

InertiaTable::updateQueryBuilderParameters('companies');$companies = QueryBuilder::for(Company::query())    ->defaultSort('name')    ->allowedSorts(['name','email'])    ->allowedFilters(['name','email'])    ->paginate(pageName:'companiesPage')    ->withQueryString();InertiaTable::updateQueryBuilderParameters('users');$users = QueryBuilder::for(User::query())    ->defaultSort('name')    ->allowedSorts(['name','email'])    ->allowedFilters(['name','email'])    ->paginate(pageName:'usersPage')    ->withQueryString();

Then, we need to apply these two changes to theInertiaTable class. There's aname andpageName method to do so.

return Inertia::render('TwoTables', ['companies' =>$companies,'users'     =>$users,])->table(function (InertiaTable$inertiaTable) {$inertiaTable        ->name('users')        ->pageName('usersPage')        ->defaultSort('name')        ->column(key:'name', searchable:true)        ->column(key:'email', searchable:true);})->table(function (InertiaTable$inertiaTable) {$inertiaTable        ->name('companies')        ->pageName('companiesPage')        ->defaultSort('name')        ->column(key:'name', searchable:true)        ->column(key:'address', searchable:true);});

Lastly, pass the correctname property to each table in the Vue template. Optionally, you may set thepreserve-scroll property totable-top. This makes sure to scroll to the top of the table on new data. For example, when changing the page of thesecond table, you want to scroll to the top of the table, instead of the top of the page.

<script setup>import {Table }from"@protonemedia/inertiajs-tables-laravel-query-builder";defineProps(["companies","users"])</script><template>  <Table:resource="companies"name="companies"preserve-scroll="table-top"  />  <Table:resource="users"name="users"preserve-scroll="table-top"  /></template>

Pagination translations

You can override the default pagination translations with thesetTranslations method. You can do this in your main JavaScript file:

import{setTranslations}from"@protonemedia/inertiajs-tables-laravel-query-builder";setTranslations({next:"Next",no_results_found:"No results found",of:"of",per_page:"per page",previous:"Previous",results:"results",to:"to"});

Table.vue slots

TheTable.vue has several slots that you can use to inject your own implementations.

SlotDescription
tableFilterThe location of the button + dropdown to select filters.
tableGlobalSearchThe location of the input element that handles the global search.
tableResetThe location of the button that resets the table.
tableAddSearchRowThe location of the button + dropdown to add additional search rows.
tableColumnsThe location of the button + dropdown to toggle columns.
tableSearchRowsThe location of the input elements that handle the additional search rows.
tableWrapperThe component thatwraps the table element, handling overflow, shadow, padding, etc.
tableThe actual table element.
headThe location of the table header.
bodyThe location of the table body.
paginationThe location of the paginator.

Each slot is provided with props to interact with the parentTable component.

<template>  <Table>    <templatev-slot:tableGlobalSearch="slotProps">      <inputplaceholder="Custom Global Search Component..."@input="slotProps.onChange($event.target.value)"      />    </template>  </Table></template>

Testing

A hugeLaravel Dusk E2E test-suite can be found in theapp directory. Here you'll find a Laravel + Inertia application.

cd appcp .env.example .envcomposer installnpm installnpm run productiontouch database/database.sqlitephp artisan migrate:fresh --seedphp artisan dusk:chrome-driverphp artisan servephp artisan dusk

Upgrading from v1

Server-side

  • TheaddColumn method has been renamed tocolumn.
  • TheaddFilter method has been renamed toselectFilter.
  • TheaddSearch method has been renamed tosearchInput.
  • For all renamed methods, check out the arguments as some have been changed.
  • TheaddColumns andaddSearchRows methods have been removed.
  • Global Search is not enabled by default anymore.

Client-side

  • TheInteractsWithQueryBuilder mixin has been removed and is no longer needed.
  • TheTable component no longer needs thefilters,search,columns, andon-update properties.
  • When using a customthead ortbody slot, you need to providethe styling manually.
  • When using a customthead, theshowColumn method has been renamed toshow.
  • ThesetTranslations method is no longer part of thePagination component, but should be imported.
  • The templates and logic of the components are not separated anymore. Use slots to inject your own implementations.

v2.1 Roadmap

  • Boolean filters
  • Date filters
  • Date range filters
  • Switch to Vite for the demo app

Changelog

Please seeCHANGELOG for more information what has changed recently.

Contributing

Please seeCONTRIBUTING for details.

Other Laravel packages

  • Laravel Analytics Event Tracking: Laravel package to easily send events to Google Analytics.
  • Laravel Blade On Demand: Laravel package to compile Blade templates in memory.
  • Laravel Cross Eloquent Search: Laravel package to search through multiple Eloquent models.
  • Laravel Eloquent Scope as Select: Stop duplicating your Eloquent query scopes and constraints in PHP. This package lets you re-use your query scopes and constraints by adding them as a subquery.
  • Laravel Eloquent Where Not: This Laravel package allows you to flip/invert an Eloquent scope, or really any query constraint.
  • Laravel FFMpeg: This package provides an integration with FFmpeg for Laravel. The storage of the files is handled by Laravel's Filesystem.
  • Laravel Form Components: Blade components to rapidly build forms with Tailwind CSS Custom Forms and Bootstrap 4. Supports validation, model binding, default values, translations, includes default vendor styling and fully customizable!
  • Laravel Mixins: A collection of Laravel goodies.
  • Laravel Verify New Email: This package adds support for verifying new email addresses: when a user updates its email address, it won't replace the old one until the new one is verified.
  • Laravel Paddle: Paddle.com API integration for Laravel with support for webhooks/events.
  • Laravel WebDAV: WebDAV driver for Laravel's Filesystem.

Security

If you discover any security related issues, please emailpascal@protone.media instead of using the issue tracker.

Credits

License

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

Sponsor this project

 

Contributors6


[8]ページ先頭

©2009-2025 Movatter.jp