Skip to content

Instantly share code, notes, and snippets.

@wuiler
Forked from vluzrmos/paginate.php
Created January 16, 2018 19:17
Show Gist options
  • Save wuiler/9fd3ca8fa5d58265b49ecfc45dd1e095 to your computer and use it in GitHub Desktop.
Save wuiler/9fd3ca8fa5d58265b49ecfc45dd1e095 to your computer and use it in GitHub Desktop.
Laravel Paginate Collection or Array
<?php
/**
* Gera a paginação dos itens de um array ou collection.
*
* @param array|Collection $items
* @param int $perPage
* @param int $page
* @param array $options
*
* @return LengthAwarePaginator
*/
public function paginate($items, $perPage = 15, $page = null, $options = [])
{
$page = $page ?: (Paginator::resolveCurrentPage() ?: 1);
$items = $items instanceof Collection ? $items : Collection::make($items);
return new LengthAwarePaginator($items->forPage($page, $perPage), $items->count(), $perPage, $page, $options);
}
@aeadedoyin
Copy link

aeadedoyin commented May 23, 2019

Is there a recomendend place to put this?

@MarcoSantana
I created a 'Utils/Utils.php' in the 'App' folder and kept every repeatedly used special function there.

@freelance-github
Copy link

I solve it can access it from collect() function like collect([2=>'some think', 9 => 'Hi'])
so go to AppServiceProvider.php and past this in boot function

/** * Bootstrap any application services. * * @return void */ public function boot() { /** * Paginate a standard Laravel Collection. * * @param int $perPage * @param int $total * @param int $page * @param string $pageName * @return array */ Collection::macro('paginate', function($perPage, $total = null, $page = null, $pageName = 'page') { $page = $page ?: LengthAwarePaginator::resolveCurrentPage($pageName); return new LengthAwarePaginator( $this->forPage($page, $perPage)->values(), $total ?: $this->count(), $perPage, $page, [ 'path' => LengthAwarePaginator::resolveCurrentPath(), 'pageName' => $pageName, ] ); }); }

@freelance-github
Copy link

I solve it

collect( [ 2 => 'Some value', 5 => 'other value' ] )->paginate(15)

https://gist.github.com/freelance-github/fe8488ff19b1a7ed67223b15c7a25b52

@HieuMinh19
Copy link

Thanks !

@senter-logistics
Copy link

Genius. You saved my life.

@Omar-Abdelrady
Copy link

thank you very much

@thiago1186
Copy link

Thanks !

@meherulsust
Copy link

Thanks, it's working for me!

@miroslav-zdravkovic
Copy link

Thanks man! Your a genious.

@262925
Copy link

262925 commented Oct 4, 2021

Thank you !!

@mdbtekny
Copy link

How can i use $collection->links()?
I got this error actually: Method Illuminate\Database\Eloquent\Collection::links does not exist.
PS: very intuitive solution!!

@tarunsankhlaRZP
Copy link

thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment