Laravel分页获取下一页

时间:2019-03-28 07:04:08

标签: laravel pagination

我有一个api,它将提取由10个项目分页的数据。这是我的逻辑:

public function getGamesResult(Request $request)
{
    // Validations
    $rules = [
        'from'=>'required|string',
        'to'=> 'required|string'
    ];

    $validator = Validator::make($request->all(), $rules);

    if ($validator->fails()) {

        // Validation failed
        return response()->json([
            'success' => false,
            'message' => $validator->messages(),
        ]);
    }

    $params =  $request->all();

    $games = Game::whereBetween("game_date", [$params["from"], $params["to"]])->paginate(10);
    $result = [];

    foreach ($games as $game) {

        $win_data = [];
        $winners = $game->result()->get();

        // Get Winning Number Records
        foreach ($winners as $win)
        {
            $winning_numbers_arr = explode(',', $win->winning_numbers);


            $win_data[] = [
                'game_id' => $win->game_id,
                'created_dt' => $win->created_dt
            ];

        }

        $result[] = [
            'game_data' => [
            'game_id' => $game->id,
            'game_date' => $game->game_date
        ],
            'winning_number' => $win_data
        ];
    }

    return response()->json([
        'success' => true,
        'data' => $result,
        'total'=> $games->total(),
        'count'=> $games->count(),
        'hasMorePages'=> $games->hasMorePages(),
        'currentPage'=> $games->currentPage()
    ]);
}

我的问题是laravel如何知道何时要获取接下来的10条记录?还是我做错了?如果总共有3000条记录,我将如何使用相同的逻辑获得下一页?

1 个答案:

答案 0 :(得分:0)

Laravel的分页器包含自动获取请求下一页的所有逻辑

https://laravel.com/docs/5.8/pagination#paginating-query-builder-results

如果您在网址末尾添加?page=2,它将获取第二页。如果未传递任何参数,则假定为第1页。