I am trying to create an API that will return all customers record from the database. But this provides pagination and filtering.,

过滤功能是一个可选的查询参数.所以不需要将其包含在查询参数中.

但我在做这件事时面临一个问题.

以下是我在CustomerController个文件中的索引方法:

    public function index(Request $request)
    {
        // Get how many item per page
        $itemPerPage = $request->query('per_page');

        // SQL Query 
        $customers = Customer::all();

        // Filter data
        if (!empty($request->name)) {
            $customers = $customers->where('name', '=', $request->name);
        }

        // Return the result as JSON
        return new CustomerCollection($customers->paginate($itemPerPage));
    }

Screenshot of Postman

或者有更好的方法将可选过滤功能与分页结合起来吗?

非常感谢.

推荐答案

您的主要问题是这一行:

$customers = Customer::all();

all()方法立即将所有customers条记录作为Collection返回,Collection没有->paginate()方法:https://laravel.com/docs/9.x/collections#available-methods.

要可选地链接,请使用->query()方法或->when()子句:

使用::query()而不是::all():

$itemPerPage = $request->query('per_page');

// SQL Query 
$customers = Customer::query();

// Filter data
if (!empty($request->name)) {
    $customers = $customers->where('name', '=', $request->name);
}

// Return the result as JSON
return new CustomerCollection($customers->paginate($itemPerPage));

使用->when()子句:

$itemPerPage = $request->query('per_page');

$customers = Customer::when(!empty($request->name), function ($query) use ($request) {
  $query->where('name', '=', $request->name);
});

return new CustomerCollection($customers->paginate($itemPerPage));

Php相关问答推荐

未找到laravel cascadeOnEdit

在WooCommerce Checkout帐单地址字段后插入自定义按钮

make dd()如何正确工作?¨

msgraph-sdk-php v2如何传递skiptoken到request?

将部分产品排除在WooCommerce的计算附加费之外

在Laravel中从动态嵌套数组中获取值

在WordPress中从CPT中删除插件

使用CODIGNITER3中的OR和AND子句进行查询

如何配置我的.env文件以在laravel的一个项目中连接两个不同的数据库?

如何用Ubuntu 22.04在VSCode中启用XDebug

标签打印机的 CSS

如何在 Laravel 迁移中使用日期时间和天数?

在 WooCommerce 我的帐户自定义部分显示未购买的产品

图像未在 Laravel Ajax Crud 中显示

使用现有的htaccess的PHP路由脚本

WooCommerce订单支付页面上的附加支付订单按钮

使用 PHP 正则表达式从仅包含具有现有顺序的顶级标签的 XML 文档中搜索和创建数组

如何在光速网络服务器中使用 apache ..htaccess

如何在 Laravel 9 中判断异常是否可报告?

PHP - 如何获取发送到脚本的查询参数