Home > Mobile >  Can I set the record limit of Laravel's paginate method with user information?
Can I set the record limit of Laravel's paginate method with user information?

Time:04-14

I'm using the paginate method of the query builder and I would like to allow the user to choose the number of items per page.

$paginate= Model::paginate($request->input('per_page'));

Doing this could I be opening a loophole for SQL Injection or is this value sanitized first?

CodePudding user response:

Such methods must be protected. This is what models are for.

But you are right, it's better to be safe than sorry and verify your premises. This is especially true with popular frameworks, because sometimes the creators crave for simplicity above everything else, often forgetting even security.

But it seems that in this case, Larvel QueryBuilder casts the perPage value to integer, making it immune to SQL injection:

protected function compileOffset(Builder $query, $offset)
{
    return 'offset '.(int) $offset;
}

Then I dug a bit into the history, and found that the protection has been added almost a decade ago, so you can be sure that with any supported version of Laravel this part is safe.

That said, validating user input is still a good idea. Even being protected from SQL injections, you don't want any unexpected behavior. I don't think 500000 or -100 are good values whatsoever. If you can see that the data is not valid, it's a good strategy to bail off already, without waiting for some bizarre things to happen. So you may consider validating this input value just like any other input, like good programmers always do.

CodePudding user response:

You can use a validator to make sure $request->input('per_page') is an integer or whatever validation you want.

documentation here : https://laravel.com/docs/9.x/validation

  • Related