Skip to content

Instantly share code, notes, and snippets.

@alepeino
Last active November 21, 2017 14:28
Show Gist options
  • Save alepeino/bdbd11d7724c275b98d553ac33cf3103 to your computer and use it in GitHub Desktop.
Save alepeino/bdbd11d7724c275b98d553ac33cf3103 to your computer and use it in GitHub Desktop.
<?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