brynj-digital / laravel-table
为 Laravel 模型提供表格功能
Requires
- php: >=5.3.0
- laravel/framework: 5.*
Requires (Dev)
- phpunit/phpunit: 4.5.*
This package is not auto-updated.
Last update: 2024-09-29 03:47:07 UTC
README
本软件包包含将 Eloquent 集合渲染为动态 HTML 表格的灵活方式。这包括可排序列、可定制单元格数据、自动分页、用户定义每页行数、批量操作处理和可扩展筛选(即将推出)的技术。
安装
在您的 composer.json
中需要此软件包
"gbrock/laravel-table": "dev-master"
将服务提供者添加到 config/app.php
中,可选地,还可以添加 Facade
'Gbrock\Table\Providers\TableServiceProvider', ... 'Table' => 'Gbrock\Table\Facades\Table',
发布视图和配置
php artisan vendor:publish
用法
为了将 Eloquent 模型渲染为 HTML 表格到视图中,首先创建一个 Table 对象,传入您的模型集合(这可以在您的控制器、仓库或任何服务类中完成)
$rows = User::get(); // Get all users from the database $table = Table::create($rows); // Generate a Table based on these "rows"
然后将该对象传递到视图中
return view('users.index', ['table' => $table]);
在您的视图中,可以使用对象的 render
函数来渲染表格对象
{!! $table->render() !!}
这将渲染类似以下的内容
排序
为了在标题中添加用于排序指定列的链接,将 Sortable
特性添加到您的模型中。由于默认不允许排序任何字段(出于安全原因),还应添加包含允许字段的 sortable
数组。
use Gbrock\Table\Traits\Sortable; class User extends Model { use Sortable; /** * The attributes which may be used for sorting dynamically. * * @var array */ protected $sortable = ['username', 'email', 'created_at'];
这将在您的模型中添加 sortable
范围,您应该在检索行时使用它。修改我们的示例,$rows = User::get()
变为
$rows = User::sorted()->get(); // Get all users from the database, but listen to the user Request and sort accordingly
现在,我们的表格将在标题中显示链接
这些链接将包含如 ?sort=username&direction=asc
的查询字符串。
分页
如果您对 Eloquent 集合进行分页,它将自动在表格下方渲染
$rows = User::sorted()->paginate(); // Get all users from the database, sort, and paginate
定制
列
在您的数据库调用/表格创建中传入第二个参数,即 列
$table = Table::create($rows, ['username', 'created_at']); // Generate a Table based on these "rows"
单元格
您可以在添加列时指定一个闭包来渲染单元格数据
// We pass in the field, label, and a callback accepting the model data of the row it's currently rendering $table->addColumn('created_at', 'Added', function($model) { return $model->created_at->diffForHumans(); });
此外,由于表格正在访问我们的模型属性,我们可以通过使用 访问器 来添加或修改任何列键
protected function getRenderedCreatedAtAttribute() { // We access the following diff string with "$model->rendered_created_at" return $this->created_at->diffForHumans(); }
默认视图优先使用 rendered_foobar
属性,如果存在,否则使用 foobar
属性。
视图
在运行 php artisan vendor:publish
后,视图文件的一个副本位于 /resources/vendor/gbrock/tables/
。您可以将此文件复制到任何位置并修改它,然后告诉您的表格使用新的视图
$table->setView('users.table');