Skip to content

Instantly share code, notes, and snippets.

@arif98741
Last active October 19, 2022 13:46
Show Gist options
  • Save arif98741/03cc6bd844275f355736c154797ca5a8 to your computer and use it in GitHub Desktop.
Save arif98741/03cc6bd844275f355736c154797ca5a8 to your computer and use it in GitHub Desktop.
This is a paginator class for generating your paginated collections from your given collections. You don't need to touch it. Your main target is to generate two collections, merge both of them and finally make a pagination.
Route::get('view-paginate-data', function () { //todo:: run this code where your business logic is written
$firstCollection = DB::table('forms')
->where('sti_type', 'Strings') //todo:: write logic according to you
->limit(5)
->get();
$secondCollection = DB::table('forms')
->where('sti_type', 'Welltest') //todo:: write logic according to you
->limit(10)
->get();
$mergedCollection = $firstCollection->merge($secondCollection);
$paginatedData = \App\Http\Controllers\PaginatorClass::paginate($mergedCollection,5); //we are showing 5 items per page.
dd($paginatedData);
});
<?php
namespace App\Http\Controllers;
use Illuminate\Container\Container;
use Illuminate\Contracts\Container\BindingResolutionException;
use Illuminate\Pagination\LengthAwarePaginator;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Collection;
class PaginatorClass extends Controller
{
/**
* Call This Method From Anywhere of your class
* @param Collection $results
* @param $showPerPage
* @return LengthAwarePaginator
* @throws BindingResolutionException
*/
public static function paginate(Collection $results, int $showPerPage)
{
$pageNumber = Paginator::resolveCurrentPage('page');
$totalPageNumber = $results->count();
return self::paginator($results->forPage($pageNumber, $showPerPage), $totalPageNumber, $showPerPage, $pageNumber, [
'path' => Paginator::resolveCurrentPath(),
'pageName' => 'page',
]);
}
/**
* Create a new length-aware paginator instance.
* This is paginator don't touch it.
* @param \Illuminate\Support\Collection $items
* @param int $total
* @param int $perPage
* @param int $currentPage
* @param array $options
* @return \Illuminate\Pagination\LengthAwarePaginator
* @throws BindingResolutionException
*/
protected static function paginator($items, $total, $perPage, $currentPage, $options)
{
return Container::getInstance()->makeWith(LengthAwarePaginator::class, compact(
'items', 'total', 'perPage', 'currentPage', 'options'
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment