Last active
November 21, 2017 14:28
-
-
Save alepeino/bdbd11d7724c275b98d553ac33cf3103 to your computer and use it in GitHub Desktop.
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 | |
namespace App; | |
use Illuminate\Contracts\Support\Responsable; | |
use Illuminate\Database\Eloquent\Builder; | |
use Illuminate\Pagination\LengthAwarePaginator; | |
trait ResponsableQuery | |
{ | |
public function newEloquentBuilder($query) | |
{ | |
return new class($query) extends Builder implements Responsable { | |
protected $perPage; | |
public function getPerPage() { | |
return $this->perPage; | |
} | |
public function setPerPage($perPage) { | |
$this->perPage = $perPage; | |
return $this; | |
} | |
public function toResponse($request) { | |
return $this->paginate($this->getPerPage())->toResponse($request); | |
} | |
protected function paginator($items, $total, $perPage, $currentPage, $options) { | |
return new class ($items, $total, $perPage, $currentPage, $options) extends LengthAwarePaginator implements Responsable { | |
public function toResponse($request) { | |
$data = $this->toArray(); | |
return response( | |
array_pull($data, 'data'), | |
200, | |
array_combine( | |
array_map(function ($key) { return "X-Paginator-$key"; }, array_keys($data)), | |
array_values($data) | |
) | |
); | |
} | |
}; | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment