在非 laravel 專案中使用 laravel 的特性 8: 分頁 pagination

ZouZhipeng發表於2021-02-24

安裝所需的包

composer require illuminate/pagination

專案入口檔案 src/index/pagination.php

由於涉及的專案都是前後端分離,就刪掉了 blade 相關的部分

<?php

require_once __DIR__ . '/../vendor/autoload.php';
// 參考 https://learnku.com/articles/54603
require_once __DIR__ . '/../orm.php';

use App\Eloquent\User;
use Illuminate\Pagination\Paginator;

// Set up a current path resolver so the paginator can generate proper links
Paginator::currentPathResolver(function () {
    return isset($_SERVER['REQUEST_URI']) ? strtok($_SERVER['REQUEST_URI'], '?') : '/';
});

// Set up a current page resolver
Paginator::currentPageResolver(function ($pageName = 'page') {
    return isset($_REQUEST[$pageName]) ? $_REQUEST[$pageName] : 1;
});

$perPage = 5;
$columns = ['*'];
$pageName = 'page';
$page = isset($_REQUEST[$pageName]) ? $_REQUEST[$pageName] : null;
$users = User::orderBy('id')->paginate($perPage, $columns, $pageName, $page);

dd($users);
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章