gbrock/laravel-table

Laravel模型的表格功能

0.3.4 2015-10-16 19:12 UTC

This package is not auto-updated.

Last update: 2024-09-28 17:07:16 UTC


README

Made for Laravel 5 Latest Tag

本包包含灵活的方式将Eloquent集合渲染为动态HTML表格。这包括可排序列、自定义单元格数据、自动分页、用户定义的每页行数、批量操作处理以及可扩展的过滤(即将推出)。

安装

在您的 composer.json 中要求此包

"gbrock/laravel-table": "dev-master"

将服务提供者添加到 config/app.php,可选地添加外观

'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() !!}

这将渲染类似以下内容

Basic example

排序

要添加在标题中按指示列排序的链接,请将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

现在,我们的表格将以标题中的链接渲染

Sortable example

链接将包含如?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');