lati111/laravel_dataproviders

为 Laravel 开发的 composer 包,通过 API 调用来创建可交互和可定制的数据表格

3.0.4 2024-09-10 10:22 UTC

This package is auto-updated.

Last update: 2024-09-13 13:21:49 UTC


README

为 Laravel 提供了一个基础,以便轻松操作数据提供者。数据提供者是数据表的 API 部分,允许您搜索、分页、排序或筛选模型,然后将这些模型加载到客户端表格中。我们建议使用我们的 TypeScript 接收脚本 来实现这一点,但您也可以自己构建。

安装

composer require lati111/laravel_dataproviders

用法

要创建一个不带额外功能的简单数据提供者

class Datatable extends Controller
{
    // Use the dataprovider trait to indicate that this is a dataprovider
    use Dataprovider;

    // Method to be called from a route
    public function data(Request $request) {
        // Get the data from the dataprovider trait.
        $data = $this->getData($request);

        // Return the data as a JsonResponse
        response()->json($data, Response::HTTP_OK);
    }

    // Implement the getContent method from the dataprovider trait to set the unmodifed data
    protected function getContent(Request $request): Builder
    {
        // Create a query for orders
        return Order::select();
    }
}

可分页

可以将数据提供者设置为可分页的,这意味着内容被分成不同的页面,可以通过导航进行浏览。要创建一个可分页的数据提供者,请按照以下步骤操作

class Datatable extends Controller
{
    // Use the dataprovider trait to indicate that this is a dataprovider
    use Dataprovider;
    // Use the paginatable trait to indicate that this dataprovider should be paginatable
    use Paginatable;

    // Method to be called from a route
    public function data(Request $request) {
        // Set the default amount of items per page (normally 10)
        $this->setDefaultPerPage(20);

        // Get the data from the dataprovider trait.
        $data = $this->getData($request);

        // Return the data as a JsonResponse
        response()->json($data, Response::HTTP_OK);
    }

    ...
}

您可以在请求中传递 pageperpage 变量。页面表示要加载哪个页面,而 perpage 设置要加载的条目数量。

{
  "page": 4,
  "perpage": 10
}

如果您想手动处理分页,例如在滚动加载项的情况下,可以使用 offset 代替 page

{
  "offset": 12,
  "perpage": 8
}

可搜索

可以将数据提供者设置为可搜索的,允许用户在数据提供者中搜索特定值。要使数据提供者可搜索,您可以执行以下操作

class Datatable extends Controller
{
    // Use the dataprovider trait to indicate that this is a dataprovider
    use Dataprovider;
    // Use the paginatable trait to indicate that this dataprovider should be paginatable
    use Searchable;

    // Method to be called from a route
    public function data(Request $request) {
        // Slows down searches but allows the dataprovider to search on aliased column defined in search fields.
        $this->setAliasSearch(true);
    
        // Get the data from the dataprovider trait.
        $data = $this->getData($request);

        // Return the data as a JsonResponse
        response()->json($data, Response::HTTP_OK);
    }

    // Implement the getSearchFields method from the Searchable trait to set what columns can be searched on
    function getSearchFields(): array
    {
        // Return an array of column names belonging to the model this dataprovider is searching on
        return ['id', 'product_name'];
    }

    ...
}

您可以在请求中传递 search 变量,指示要在选定列中搜索的术语。

{
  "search": "USB"
}

可排序

可以将数据提供者设置为可排序的,允许用户指定要排序的列。要使数据提供者可排序,您可以执行以下操作

class Datatable extends Controller
{
    // Use the dataprovider trait to indicate that this is a dataprovider
    use Dataprovider;
    // Use the paginatable trait to indicate that this dataprovider should be paginatable
    use Sortable;
    
    function __construct() {
        //when using an aliased column, you can set it in the column aliases array to replace any sorting of `time_since_order` with `created_at`
        $this->columnAliases = ['time_since_order' => 'created_at']
    }

    // Method to be called from a route
    public function data(Request $request) {
        // Get the data from the dataprovider trait.
        $data = $this->getData($request);

        // Return the data as a JsonResponse
        response()->json($data, Response::HTTP_OK);
    }

    // Implement the getAllowedSortColumns method from the Sortable trait to set what columns can be sorted on
    function getAllowedSortColumns(): array
    {
        // Return an array of column names belonging to the model this dataprovider is are allowed to be sorted on
        return ['total_price', 'price', 'amount', 'created_at'];
    }

    ...

}

您可以通过请求变量传递一个包含可排序信息的 JSON 数组,键为 'sort'。数组应如下所示

{
  "sort": {
    "price": "desc",
    "created_at": "desc"
  }
}

可过滤

可以将数据提供者设置为可过滤的,允许用户根据特定值进行过滤。要使数据提供者可排序,您可以执行以下操作

class Datatable extends Controller
{
    // Use the dataprovider trait to indicate that this is a dataprovider
    use Dataprovider;
    // Use the paginatable trait to indicate that this dataprovider should be paginatable
    use Filterable;

    // Method to be called from a route to get the data
    public function data(Request $request) {
        // Get the data from the dataprovider trait.
        $data = $this->getData($request);

        // Return the data as a JsonResponse
        response()->json($data, Response::HTTP_OK);
    }
    
    // Method to be called from a route to get filter options
    public function getFilters(Request $request) {
        // Gets either a list of available filters, or a list of available options for a filter if one is specified
        $data = $this->getFilterData($request);

        // Return the data as a JsonResponse
        response()->json($data, Response::HTTP_OK);
    }

    // Implement the getFilterList method from the Filterable trait to set what filters exist
    function getFilterList(): array
    {
        return [
            'customer' => new CustomerFilter(),
            'product' => new ProductFilter(),
        ];
    }

    ...
}

过滤器必须实现 DataproviderFilterInterface 接口才能工作,并按以下方式构造

class CustomerFilter implements DataproviderFilterInterface
{
    // Apply the filter to a query
    public function handle(Builder $builder, string $operator, string $value): Builder
    {
        // Perform query actions necessary to enforce the filter
        $builder->where('customer_id', $operator, $value);

        return $builder;
    }

    // Get the details about this filter matching the right format
    public function getInfo(): array
    {
        return [
            'option' => 'customer',
            'operators' => [
                ['operator' => '=', 'text' => 'is'],
                ['operator' => '!=', 'text' => 'is not'],
            ],
            'options' => Product::distinct()->pluck('customer_id'),
        ];
    }
}

您可以通过请求变量传递一个包含过滤器的 JSON 数组,键为 'sort'。数组应如下所示

{
  "filters": [
    {
      "filter": "customer",
      "operator": "!=",
      "value": "34"
    }
  ]
}

要求

  • PHP ^8.1
  • Laravel ^10.0