Last active
January 26, 2022 13:04
-
-
Save zuxbrt/1be6cfa164c7fad1b68d9e2842d5123e to your computer and use it in GitHub Desktop.
Laravel Pagination helper class
This file contains 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 | |
// composer json | |
// "php": "^7.3|^8.0", | |
// "laravel/framework": "^8.75" | |
namespace App\Helpers; | |
class Pagination | |
{ | |
public $model; | |
public function __construct($model) | |
{ | |
$this->model = $model; | |
} | |
public function paginate(int $page, int $numberOfResults) | |
{ | |
$allItems = $this->model::orderBy('id', 'desc') | |
->skip($page * $numberOfResults - $numberOfResults) | |
->take($numberOfResults) | |
->select("*") | |
->get(); | |
$numberOfPages = ceil($this->model::all()->count() / $numberOfResults); | |
$pages = array(); | |
for($i = 1; $i <= $numberOfPages; $i++){ | |
array_push($pages, $i); | |
} | |
$results = $allItems->toArray(); | |
// response for API in current example | |
$response["numberOfPages"] = $pages; | |
$response["results"] = $results; | |
return response($response); | |
} | |
} | |
// usage in controller | |
// $request parameters (GET Method) (*Illuminate\Http\Request instance): | |
// {your url}?page=1&results=100 | |
public function all(Request $request) | |
{ | |
$pagination = new Pagination(Model::class); | |
return $pagination->paginate($request->page, $request->results); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment