Bill Garrison Bill Garrison - 2 years ago 528
PHP Question

Laravel 5.2 - filtering on a custom attribute and then paginating

So I know how to paginate using

and I know how to filter based on an Accessor (a
on the collection). However, paginate takes in a query builder and where() on a collection returns a collection.

So if I want to get a bunch of items / filter by a custom attribute and then paginate the result do i do that??


public function getRequiredToReportAttribute()
// return boolean based off of complicated business logic

index method:

public function index()
//what im doing (redacted)
$employers = (new App\Employers')->paginate($this->perPage);

// what I would like to be doing
$employers = (new App\Employers)->where('required_to_report', '=', true)->paginate($this->perPage);

return $this->sendResponse($employers);

Answer Source

In the case that you want to work with accesors, you could by iterating the collection after you get your query, something like this:

 $result = Model::get()->filter(function($item) {
    return $item->require_to_report === true;

Here you have all records of your model and then you could create a manual paginator:

 $paginator = new Illuminate\Pagination\Paginator($result, 10);

you have with this approach a weakness when you have too many records, the performance could be affected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download