【问题标题】:How to add filter and pagination with Laravel Eloquent如何使用 Laravel Eloquent 添加过滤器和分页
【发布时间】:2022-07-11 23:12:09
【问题描述】:

我正在尝试创建一个 API,它将返回数据库中的所有客户记录。但这提供了分页和过滤。,

过滤功能是一个可选的查询参数。所以没有必要将它包含在查询参数中。

但我在这样做时遇到了问题。

这是我在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));
    }

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

谢谢。

【问题讨论】:

  • 您是否在寻找 Laravel 分页 或 Laravel API 分页 教程?查看官方文档以及他们如何使用它:Laravel 9.x: pagination。这也适用于旧版本。
  • 您好@PeterKrebs,您的回复。我已经阅读了官方文档。但我发现我无法在 where 子句之前或之后加入分页。但在我的场景中,我需要过滤部分是可选的,所以我不能在 Customer:: 之后添加 where 子句
  • @TimLewis 感谢您的解决方案。阅读您的回复后,我只知道有一个 query() 子句。非常感谢!您的解决方案在我这边非常有效。再次感谢!

标签: php laravel


【解决方案1】:

您的主要问题是这一行:

$customers = Customer::all();

all() 方法立即将所有customers 记录返回为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));

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 1970-01-01
    • 2019-03-01
    • 2016-02-29
    • 2020-02-27
    • 2015-04-21
    相关资源
    最近更新 更多