Bill Garrison Bill Garrison - 6 months ago 284
PHP Question

Laravel 5.2 - filtering on a custom attribute and then paginating

So I know how to paginate using

paginate()
and I know how to filter based on an Accessor (a
where()
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 set....how do i do that??

Accessor:

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

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.

Comments