Last active
July 13, 2023 03:42
-
-
Save mahbodsh/1c9f181bdb96c15b98247aedea168349 to your computer and use it in GitHub Desktop.
Pagination helper in laravel resource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Resources; | |
use App\Helpers\ResourcePaginationHelper; | |
use Illuminate\Http\Resources\Json\ResourceCollection; | |
class ProductsResourceCollection extends ResourceCollection | |
{ | |
/** | |
* Transform the resource collection into an array. | |
* | |
* @param \Illuminate\Http\Request $request | |
* @return array | |
*/ | |
public function toArray($request) | |
{ | |
return [ | |
'data'=> $this->collection->map(function ($item){ | |
return[ | |
'price' => $item->price, | |
'color' => $item->color, | |
'amount ' => $item->amount , | |
]; | |
}), | |
'links' => ResourcePaginationHelper::generateLinks($this, 'products.search') | |
]; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helpers; | |
use Illuminate\Http\Resources\Json\ResourceCollection; | |
class ResourcePaginationHelper | |
{ | |
public static function generateLinks (ResourceCollection $resouceCollection, string $routeName) | |
{ | |
$totalPages = $resouceCollection->total(); | |
$nextPrevPages = self::getNextPrevPages(); | |
$paginationData = [ | |
'total' => $totalPages, | |
'links' => [], | |
'next' => route($routeName, 'page='.$nextPrevPages['next']), | |
'prev' => $nextPrevPages['prev'] != null ? route($routeName, 'page='.$nextPrevPages['prev']): null | |
]; | |
for($i = 1; $i <= $totalPages; $i++) | |
{ | |
$paginationData['links']["$i"] = route($routeName, 'page='.$i); | |
if($i == 1) | |
$paginationData['first_page'] = route($routeName, 'page='.$i); | |
if($i == $totalPages) | |
$paginationData['last_page'] = route($routeName, 'page='.$i); | |
} | |
return $paginationData; | |
} | |
public static function getNextPrevPages() | |
{ | |
$nextPrevPages = ['prev' => null, 'next' => 1]; | |
if(isset($_GET['page'])) | |
{ | |
$nextPrevPages['next'] = $_GET['page'] + 1; | |
$nextPrevPages['prev'] = $_GET['page'] == 1 ? null : $_GET['page'] - 1; | |
} | |
return $nextPrevPages ; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment