appolous/laratables

为 Laravel DataTables 提供Ajax支持

1.0 2024-06-05 05:24 UTC

This package is auto-updated.

Last update: 2024-09-03 10:35:45 UTC


README

Latest Stable Version Total Downloads MIT Licensed Buy Me A Coffee

包状态

由于原始包不再处于活跃开发状态,我们仅更新此包以支持 Laravel 的最新版本。其他一切保持不变。

支持 Laravel 7.x - 11.x

Laratables

一个 Laravel 包,用于处理 Datatables 的服务器端 Ajax。

目录

介绍

此包可以帮助处理将 Eloquent 模型中的数据显示到具有 Ajax 支持的 datatables 中的简单需求。此外,使用简单的关系和自定义列值。Laratables 目前不与 Datatables Editor 兼容。

如何使用

基本方法是,您可以在客户端指定 Datatable 配置和列,就像您没有进行任何重大更改一样,然后在服务器端调用一个方法来处理 Ajax 调用。包将创建必要的查询以获取数据并使搜索和排序功能自动工作。如果需要,您可以通过在 Eloquent 模型或自定义类中添加方法来在各个阶段自定义查询/数据/逻辑。

客户端

$('#users-table').DataTable({
    serverSide: true,
    ajax: "{{ route('admin.users.datatables') }}",
    columns: [
        { name: 'id' },
        { name: 'name' },
        { name: 'email' },
        { name: 'role.name', orderable: false },
        { name: 'action', orderable: false, searchable: false }
    ],
    ...
});

⚠️ 重要提示 ⚠️ - 客户端代码决定了应获取哪些列。如果您在公共页面上显示表,恶意用户可以修改 HTTP 请求以获取相应表的或其他相关表的列数据。强烈建议在返回数据之前验证请求。

服务器端

use App\User;
use Freshbitsweb\Laratables\Laratables;
...
return Laratables::recordsOf(User::class);

有多种方式可以自定义查询/数据/逻辑。有关详细信息,请参阅下面的 自定义 部分。

⬆ 返回顶部

演示仓库

  1. https://github.com/freshbitsweb/laratables-demo-one-to-many
  2. https://github.com/freshbitsweb/laratables-demo-customize-column
  3. https://github.com/freshbitsweb/laratables-demo-basic
  4. https://github.com/freshbitsweb/laratables-demo-many-to-many
  5. https://github.com/freshbitsweb/laratables-demo-one-to-many-polymorphic
  6. https://github.com/freshbitsweb/laratables-demo-one-to-one

要求

安装

在您的终端/cmd 中运行此命令以安装包

composer require freshbitsweb/laratables

可选,您可以在终端/cmd 中运行此命令以导入配置文件

php artisan vendor:publish --tag=laratables_config

⬆ 返回顶部

自定义

按照“如何使用”部分的步骤,您应该能在一分钟内使用简单的 datatables 示例开始运行。然而,许多 datatables 需要自定义能力。第一个用例是应用额外的 where 条件到查询或加载额外的关联。

要实现这一点,您可以简单地通过将闭包/可调用作为第二个参数传递给 recordsOf() 方法。它应该接受底层查询作为参数,并在应用条件后返回它

use App\User;
use Freshbitsweb\Laratables\Laratables;
...
return Laratables::recordsOf(User::class, function($query)
{
    return $query->where('active', true);
});

有许多其他选项可以自定义查询/数据/逻辑。您可以在 模型或自定义类 中添加以下任何方法(它们以 laratables 字符串开头),以保持模型整洁和干净。如果您希望使用自定义类,请将自定义类的名称作为 recordsOf() 方法的第二个参数指定

use App\User;
use Freshbitsweb\Laratables\Laratables;
use App\Laratables\User as UserLaratables;
...
return Laratables::recordsOf(User::class, UserLaratables::class);

⬆ 返回顶部

控制查询

如果您希望在每次使用模型以显示 Laratable 时都应用条件,请将 laratablesQueryConditions() 静态方法添加到模型/自定义类中。

/**
 * Fetch only active users in the datatables.
 *
 * @param \Illuminate\Database\Eloquent\Builder
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function laratablesQueryConditions($query)
{
    return $query->where('active', true);
}

此方法接受并返回一个 $query 对象。

控制关系查询

您还可以通过定义闭包来控制关系查询,该闭包可以在贪婪加载关系记录时使用。静态方法名称格式为laratables[关系名]RelationQuery

/**
 * Eager load media items of the role for displaying in the datatables.
 *
 * @return callable
 */
public static function laratablesRoleRelationQuery()
{
    return function ($query) {
        $query->with('media');
    };
}

将相关表连接到查询

还可以使用laratablesQueryConditions()方法在基表上添加连接。如果需要根据相关模型定义自定义搜索和排序,这尤其有用,例如

/**
 * Join roles to base users table.
 * Assumes roles -> users is a one-to-many relationship
 *
 * @param \Illuminate\Database\Eloquent\Builder
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function laratablesQueryConditions($query)
{
    return $query->join('roles', 'roles.id', 'users.role_id');
}

注意 - 如果根据连接表的列进行搜索/筛选,您还需要确保它们包含在所选列中。以下是一些实现此操作的方法选项

  • 在上述->select()方法中链接 - 例如$query->join(...)->select(['roles.name as role_name']),或者
  • 使用下面所述的laratablesAdditionalColumns()方法,如选择额外列

⬆ 返回顶部

自定义列

通常,我们需要一个或多个不在数据库表中存在的列。最常见的一个例子是'操作'列,用于提供编辑或删除记录的选项。您可以在模型/自定义类中添加一个静态方法laratablesCustom[列名]()来指定自定义列值。根据我们的示例,它可能是

/**
 * Returns the action column html for datatables.
 *
 * @param \App\User
 * @return string
 */
public static function laratablesCustomAction($user)
{
    return view('admin.users.includes.index_action', compact('user'))->render();
}

如您所观察到的,您将作为参数接收记录的eloquent对象,以在方法中使用记录详细信息。

⬆ 返回顶部

关系列

我们还需要显示相关模型的数据,对吧?在这里,这很简单。对于简单的关系,无需在服务器端进行任何操作。只需在客户端的列数组中指定关系的名称和列的名称。

columns: [
    ...
    { name: 'role.name', orderable: false },
    ...
],

在Laravel中,不支持按关系列排序记录,因为主表记录首先被检索,然后执行另一个查询来检索相关表的记录。因此,您应始终将关系表列的orderable: false

注意 - 该包目前不支持嵌套关系。您可以通过自定义列功能获取嵌套关系数据,但请确保您贪婪加载了关系记录。

⬆ 返回顶部

自定义列值

有时,您可能需要在将列值显示在表格中之前对其进行自定义。只需在您的eloquent模型/自定义类中添加一个静态方法laratables[列名]()即可。

/**
 * Returns truncated name for the datatables.
 *
 * @param \App\User
 * @return string
 */
public static function laratablesName($user)
{
    return Str::limit($user->name, 15);
}

您还可以通过添加格式为laratables[关系名][列名]()的静态方法来自定义关系列。

这些静态方法使用记录的eloquent对象作为参数在eloquent模型/自定义类上调用。

注意 - 在v1.*.*版本中,这些方法是普通方法。

⬆ 返回顶部

搜索

Datatables提供搜索功能,可以根据任何显示列的值过滤结果。虽然此包自动应用orWhere条件与like运算符,但您可以为任何列添加自己的条件。我们为此提供静态方法laratablesSearch[列名]()

/**
 * Adds the condition for searching the name of the user in the query.
 *
 * @param \Illuminate\Database\Eloquent\Builder
 * @param string search term
 * @return \Illuminate\Database\Eloquent\Builder
 */
public static function laratablesSearchName($query, $searchValue)
{
    return $query->orWhere('first_name', 'like', '%'. $searchValue. '%')
        ->orWhere('surname', 'like', '%'. $searchValue. '%')
    ;
}

如果任何列是关系列,该包足够智能,可以应用带有必要闭包的orWhereHas查询来相应地过滤记录。您可以添加laratablesSearch[关系名][列名]()静态方法到您的eloquent模型/自定义类中覆盖该行为。

注意 - 您可以在Datatables配置(客户端)中添加searchable: false到任何列以防止对该列进行搜索操作。或者,您也可以将列名添加到配置文件中的non_searchable_columns数组中。

⬆ 返回顶部

排序(排序)

默认情况下,常规表列的排序功能是启用的。也支持多列排序。对于关系列或自定义列,您应该将 orderable: false 添加到 Datatables 列配置中,或者添加一个静态方法 laratablesOrder[ColumnName]() 并返回用于排序记录的主表列名称。例如,如果您的表包含 first_name 且 Datatables 只有 name,您可以添加

/**
 * first_name column should be used for sorting when name column is selected in Datatables.
 *
 * @return string
 */
public static function laratablesOrderName()
{
    return 'first_name';
}

您还可以通过添加一个静态方法 laratablesOrderRaw[ColumnName]() 并返回我们将在查询的 orderByRaw() 中放置的原始语句来按原始语句排序行。函数接收 $direction 变量,该变量将是 ascdesc

/**
 * first_name and last_name columns should be used for sorting when name column is selected in Datatables.
 *
 * @param string Direction
 * @return string
 */
public static function laratablesOrderRawName($direction)
{
    return 'first_name '.$direction.', last_name '.$direction;
}

⬆ 返回顶部

选择附加列

我们已经以这种方式编写了包,其中查询只从数据库表中选择所需的列。如果您在自定义列值时需要其他列的值,您可以在 laratablesAdditionalColumns() 静态方法中指定它们。例如,如果您在表中具有 first_namesurname,您正在使用自定义列 name,您可以添加

/**
 * Additional columns to be loaded for datatables.
 *
 * @return array
 */
public static function laratablesAdditionalColumns()
{
    return ['first_name', 'surname'];
}

⬆ 返回顶部

指定附加可搜索列

如果您需要在未在 Datatables 中显示的表列中搜索值,您可以在 laratablesSearchableColumns() 静态方法中的数组中指定它们。例如,如果您在表中具有 first_namesurname,并且您希望用户能够通过这些列进行搜索,即使它们未在 Datatables 中显示,您也可以添加

/**
 * Additional searchable columns to be used for datatables.
 *
 * @return array
 */
public static function laratablesSearchableColumns()
{
    return ['first_name', 'surname'];
}

⬆ 返回顶部

Carbon 实例的日期格式

默认情况下,Laravel 将 created_atupdated_at 作为 Carbon 实例处理,您也可以将表中的任何其他列也作为 Carbon 实例处理。此包有一个配置选项 date_format,用于指定返回给 Datatables 的日期格式。默认格式为 'Y-m-d H:i:s'。

修改获取的记录

有时,我们需要在记录已经检索到之后与记录一起工作。您可以将 laratablesModifyCollection() 静态方法添加到您的模型/自定义类中,以玩转集合并返回更新后的一个。注意,如果您从集合中添加/删除任何项,Datatables 的计数将不匹配。

/**
 * Set user full name on the collection.
 *
 * @param \Illuminate\Support\Collection
 * @return \Illuminate\Support\Collection
 */
public static function laratablesModifyCollection($users)
{
    return $users->map(function ($user) {
        $user->full_name = $user->first_name . ' '. $user->last_name;

        return $user;
    });
}

⬆ 返回顶部

额外的 data- Datatables 属性

Datatables 接受 每个记录的额外 data- 属性。以下是由此包支持的

  1. DT_RowId:此数据属性默认添加到每个记录中。您可以通过更新 row_id_prefix 配置选项来设置记录 ID 的前缀。

  2. DT_RowClass:您可以将 laratablesRowClass() 静态方法添加到您的模型/自定义类中,并返回一个 html 类名称。示例

/**
 * Specify row class name for datatables.
 *
 * @param \App\User
 * @return string
 */
public static function laratablesRowClass($user)
{
    return $user->is_active ? 'text-success' : 'text-warning';
}

注意 - 在 v1.*.* 中,此方法是常规方法。

  1. DT_RowData:您可以将 laratablesRowData() 静态方法添加到您的模型/自定义类中,并返回一个具有属性名称作为键及其对应值的数组。示例
/**
 * Returns the data attribute for url to the edit page of the user.
 *
 * @param \App\User
 * @return array
 */
public static function laratablesRowData($user)
{
    return [
        'edit-url' => route('admin.user.edit', ['user' => $user->id]),
    ];
}

注意 - 在 v1.*.* 中,此方法是常规方法。

作者

有关参与此项目的 贡献者 列表,请参阅。

许可证

此项目根据 MIT 许可证许可 - 有关详细信息,请参阅 LICENSE 文件

免费软件

您可以使用此包,但如果它进入您的生产环境,我将非常感谢您为世界买一棵树。

现在众所周知,解决气候危机并防止气温上升超过 1.5C 的最佳工具之一是 植树。如果您为我们的森林做出贡献,您将为当地家庭创造就业机会并恢复野生动物栖息地。

您可以在以下位置购买为我们的森林的树 offset.earth/treeware

了解更多关于Treeware的信息,请访问treeware.earth

特别感谢