原生 Laravel 的 Collection 極好用!
想要補充一個 Paginate 功能,只要簡單一段 code 即可!
新增功能常見的方法多為 helper 或是 繼承複寫,
但這次我們是要在 Collection 上直接 新增paginate,
而 Laravel 提供了 Macroable 的 Traits ,讓寫法變得十分的簡潔【 macro 】!

新增方法
尋找一個適合的 ServiceProvider 或是 創建一個新的ServiceProvider,
把 macro,放入 boot() 中!
if (!Collection::hasMacro('paginate')) {
Collection::macro('paginate', function ($perPage, $total = null, $page = null, $pageName = 'page') {
$page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName);
return new LengthAwarePaginator(
$this->forPage($page, $perPage),
$total ?: $this->count(),
$perPage,
$page,
[
'path' => LengthAwarePaginator::resolveCurrentPath(),
'pageName' => $pageName,
]
);
});
}
使用方法
collect($arr)->paginate(10)
