如何使用laravel分页正确显示当前数据?

问题描述 投票:0回答:1

我在 Laravel 10 中分页时遇到问题。我已经从数据库生成了 13 条数据,并且位于第 1 页,所以我希望看到类似的内容

“显示 13 个结果中的 1 到 8 个”

但是,我的代码显示了消息

“显示 13 个结果中的 1 到 13 个”

我做错了什么?感谢任何帮助。

这是我的代码:

    public function index(Request $request)
    {
        $client = new \GuzzleHttp\Client();

        $perPage = $request->query('per_page') ? : 8;
        $page = $request->query('page') ? : 1;

        $url = "http://localhost/api/culinary?page=$page&per_page=$perPage";

        $response = $client->request('GET', $url);

        $json = json_decode((string)$response->getBody(), true);

        $paginatedResult = new LengthAwarePaginator(
            $json, // the data to be paginated
            count($json), // total count of the data
            $perPage, // number of data shown per page
            $page, // current page number
        );

        $view_data = [
            'title' => 'Browse Culinary',
            'data' => $paginatedResult,
        ];
        return view('culinary.index', $view_data);
    }

我在

index.blade.php
中使用此代码来显示分页部分

{{ $data->withQueryString()->withPath('/culinary')->links() }}
php laravel pagination laravel-10 laravel-pagination
1个回答
0
投票

您应该对传递给分页器的项目进行切片。来自文档

手动创建分页器实例时,您应该手动“切片”传递给分页器的结果数组。

因此将其传递给您的分页器:

$offset = ($page - 1) * $perPage;

$paginatedResult = new LengthAwarePaginator(
    array_slice($json, $offset, $perPage), // paginated data
    count($json), // total count of the data
    $perPage, // number of data shown per page
    $page, // current page number
);
© www.soinside.com 2019 - 2024. All rights reserved.