Created
April 8, 2019 02:30
-
-
Save robjbrain/6dd5346e5844eff598639af0654d5b42 to your computer and use it in GitHub Desktop.
Simple way to optionally paginate a request
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 | |
/* | |
This will avoid doing this all the time. | |
public function index(Request $request) | |
{ | |
$query = Model::with(['foo, 'bar'); | |
return ModelResource::collection($request->input('per_page') | |
? $query->paginate($request->input('per_page') | |
: $query->get() | |
); | |
} | |
And allow this: | |
public function index(Request $request) | |
{ | |
return ModelResource::collection(Model::with(['foo, 'bar')->getOrPaginate()); | |
} | |
Just add this to your base model: | |
/** | |
* Create a new Eloquent query builder for the model. | |
* | |
* @param \Illuminate\Database\Query\Builder $query | |
* @return \App\Eloquent\Builder|static | |
*/ | |
public function newEloquentBuilder($query) | |
{ | |
return new Builder($query); | |
} | |
*/ | |
namespace App\Eloquent; | |
use Illuminate\Database\Eloquent\Builder as LaravelBuilder; | |
class Builder extends LaravelBuilder | |
{ | |
/** | |
* @param array $columns | |
* @param string $pageName | |
* @param null $page | |
* @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|\Illuminate\Database\Eloquent\Collection | |
*/ | |
public function getOrPaginate($columns = ['*'], $pageName = 'page', $page = null) | |
{ | |
if ($perPage = request()->input('per_page')) { | |
return $this->paginate($perPage, $columns = ['*'], $pageName, $page); | |
} | |
return $this->get($columns); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment