panthro's avatar

Passing a parameter to control the number of items returned by pagination?

I'm looking for a way to pass a value to my paginate method, so I can control the number of results for my GET request:

->cursorPaginate($items)

I know I can get the value from the query string, and even set a default if not present. But I am wondering how do you go about setting a min and max setting, e.g. so a user cannot access 10,000 records at once?

I'm aware of this package but it does not work with cursorPaginate.

I'm also aware you could just do a quick test on the value of the query string, but I need this throughout my application.

Any ideas?

0 likes
4 replies
Snapey's avatar

I would use validation to check the limit is valid

Rule::in([10,25,50,100]);
panthro's avatar

@Snapey thanks, anyway to attach this through every paginate request rather than in every controller or request?

Snapey's avatar
Snapey
Best Answer
Level 122

You could maybe attach it to your model as a fake scope

in paginated model;

public function scopeValidLimit($query)
{
    abort_unless(in_array(request()->get(perPage,10),[10,25,50,100]),500);
}

then use it like

$data = Model::validLimit()->paginate(request()->get(perPage,10));

If the user tampers with the view or the query string, they get a 500 error.

You could put this in a trait and include it in all paginated models.

but its blurring the lines a little.

(code written here in laracasts so may have typos)

1 like

Please or to participate in this conversation.